Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/433.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 根据href更改按钮文本_Javascript - Fatal编程技术网

Javascript 根据href更改按钮文本

Javascript 根据href更改按钮文本,javascript,Javascript,我试图根据slug中的国家更改一些按钮文本,例如法国的“fr”。此功能仅用于拾取第一个装载的Meer,无论发生什么情况。知道我错过了什么吗 window.onload = function(){ if(window.location.href.indexOf("nl") > -1){ var x = document.getElementsByClassName('juicer-button')[0];

我试图根据slug中的国家更改一些按钮文本,例如法国的“fr”。此功能仅用于拾取第一个装载的Meer,无论发生什么情况。知道我错过了什么吗

  window.onload = function(){
            if(window.location.href.indexOf("nl") > -1){                
              var x = document.getElementsByClassName('juicer-button')[0];
              x.innerHTML = "Meer laden";      
            }
            else if(window.location.href.indexOf("de") > -1){                
              var y = document.getElementsByClassName('juicer-button')[0];
              y.innerHTML = "Mehr laden";      
            }
            else if(window.location.href.indexOf("fr") > -1){
              var z = document.getElementsByClassName('juicer-button')[0];
              z.innerHTML = "Charger plus";      
            }
            else if(window.location.href.indexOf("it") > -1){                
              var a = document.getElementsByClassName('juicer-button')[0];
              a.innerHTML = "Carica altro";      
            }
            else{''}
          }

在演示中对细节进行了评论

/**
*countrySlug(url)
*@参数:url{string}
*/
//A在最后一个角色之后得到这个角色`/`
//B一系列国家
//按钮的文本数组
//D match将是与slug匹配的国家的索引号
//E应用该索引号在文本数组中查找对应的字符串
const countrySlug=url=>{
让slug=url.split('/').pop();//A
const countries=['nl','de','fr','it'];//B
const text=[“米尔负载”、“米尔负载”、“充电器升级版”、“加勒比阿尔特罗”];//C
让match=countries.indexOf(slug);//D
返回文本[匹配];//E
}
/*
document.querySelector()查找#id、.class、标记等。
.textContent设置/获取元素(标记)中的文本
*/
document.querySelector('.btn')。textContent=countrySlug('https://example.com/de');

这个正则表达式并不是最难做到的:

window.onload = function()
{
  const CountryText = { 'nl': 'Meer laden'
                      , 'de': 'Mehr laden'
                      , 'fr': 'Charger plus'
                      , 'it': 'Carica altro' };

  let CountryRef = window.location.href.match(/nl|de|fr|it/g);

  if(CountryRef)
  {
    document.querySelector(".juicer-button").textContent = CountryText[CountryRef[0]];
  }
}

那么,在这种情况下,
window.location.href
的内容是什么?也许在URL的某个地方总是包含“nl”?如果它只选择第一个,这意味着你的URL总是包含slug“nl”。你能列举一些URL使用的例子吗?这样的代码不应该依赖URL;有更好的阅读语言的方法。如果服务器添加类似于
的语言,例如
document.getElementsByClassName('juice-button')[0]