Select keeps reverting after programmatic change of value

时间:2018-02-26 17:35:51

标签: javascript html

When a page is loaded, I would like it to set the correct value for the <select> box. I did this by using onload on the body to call a function, I then got the url and extracted the language from the url (e.g http://example.com/en/index.html is now 'en'). Once I have this, I am then trying to change the selected value for the select box to the appropriate tag. However, when using Chrome, I can see that it attempts to change but around half a second later it then flips back over to the default ("English"). What am I doing wrong?

I have also tried .selected = true; to no avail.

function checkLang() {
  var url = location.href;
  var curLang = url.substring(0, url.lastIndexOf('/'));
  curLang = curLang.substr(curLang.length - 2);

  if (curLang == "en") {
    document.getElementById("lang").getElementsByTagName("value")["english"].selected = "selected";
  } else if (curLang == "fr") {
    document.getElementById("lang").getElementsByTagName("value")["french"].selected = "selected";
  } else if (curLang == "de") {
    document.getElementById("lang").getElementsByTagName("value")["german"].selected = "selected";
  } else if (curLang == "es") {
    document.getElementById("lang").getElementsByTagName("value")["spanish"].selected = "selected";
  }
}
<select id="lang" onchange="changeLang()" autocomplete="off">
  <option value="english">English</option>
  <option value="spanish">Spanish</option>
  <option value="french">French</option>
  <option value="german">German</option>
</select>

1 个答案:

答案 0 :(得分:0)

第一个错误是选择自己 onchange="changeLang()" ,而脚本中的函数名称是 checkLang()

第二件事是你错误地引用了选项标签,而不是这个

// There is no tag called "value"
document.getElementById("lang").getElementsByTagName("value")["english"].selected = "selected";

应该是这样的

// 0 here points to the first option tag
document.getElementById('lang').options.selectedIndex = 0;

或者像这样

document.getElementById("lang").options[0].selected = 'selected';

或者,如果你想保持逻辑,你必须修改它才能工作

// the tag name here is "option" not "value"
// point to a certain option tag using the index i.e. 0,1,2,...
document.getElementById("lang").getElementsByTagName("option")[0].selected = "selected";

如果您想在每次加载页面时执行此功能以从网址检测语言并使用当前语言设置选择,那么您的正文标记应该与此<body onload="checkLang();">类似,并从中删除onchange="checkLang();"选择标签