根据href更改按钮文字

时间:2019-05-15 23:02:37

标签: javascript

我正在尝试根据子弹中的国家/地区更改一些按钮文本,例如法国的“ 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{''}
          }

2 个答案:

答案 0 :(得分:1)

演示中评论的详细信息

/**
 *countrySlug(url)
 *@ Params: url {string} 
 */
//A Get the part after the last `/`
//B Array of countries
//C Array of text for button
//D match will be the index number of country that matches the slug
//E Apply that index number to find the corresponding string in the text array
const countrySlug = url => {
  let slug = url.split('/').pop(); //A
  const countries = ['nl', 'de', 'fr', 'it']; //B
  const text = ["Meer Laden", "Mehr Laden", "Charger Plus", "Carica Altro"]; //C
  let match = countries.indexOf(slug); //D
  return text[match]; //E
}

/*
document.querySelector() to find an #id, .class, tag, etc.
.textContent to set/get text within an element (tag)
*/
document.querySelector('.btn').textContent = countrySlug('https://example.com/de');
<button class='btn'></button>

答案 1 :(得分:1)

此正则表达式不是最难的事情:

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]];
  }
}