在Internet Explorer中使用Javascript选择正确的选项

在Internet Explorer中使用Javascript选择正确的选项,javascript,html,Javascript,Html,当触发javascript事件时,Internet Explorer没有正确选择选项,我有一个问题 我在谷歌地图上追踪一个标记的事件。移动标记时,我希望从选择列表中选择正确的国家 切换国家/地区选择的部分代码: <script type="text/javascript"> //... document.getElementById("id_country").value = country; //... </script> //... document.getEle

当触发javascript事件时,Internet Explorer没有正确选择选项,我有一个问题

我在谷歌地图上追踪一个标记的事件。移动标记时,我希望从选择列表中选择正确的国家

切换国家/地区选择的部分代码:

<script type="text/javascript">
//...
document.getElementById("id_country").value = country;
//...
</script>

//...
document.getElementById(“id_country”)。值=国家;
//...
它在谷歌浏览器中运行良好。我知道地图返回的国家名称与选项字段值中的名称匹配。在Internet Explorer中,什么都不会发生

<select id="id_country" name="country">
    <option value="Afghanistan">Afghanistan</option>
    <option value="Aland Islands">Aland Islands</option>
    <!--...-->
</select>

阿富汗
阿兰群岛

如何让Internet Explorer选择正确的选项(不使用jquery)?

您需要遍历document.getElementById('id_country')的选项集合,并将匹配选项的“selected”属性设置为字符串“selected”

属性将起作用,但正如Afshin所说,您需要首先迭代选项

var elCountry = document.getElementById("id_country");
var options = elCountry.options;
for (var i = 0; i < options.length; i++) {
    if (options[i].value == country) {
        elCountry.selectedIndex = i;
    }
}
var elCountry=document.getElementById(“id_country”);
var options=elCountry.options;
对于(变量i=0;i
下面是一个代码示例,演示@afshin的答案(谢谢!):

功能设置国家/地区选项(国家/地区){
const selectEl=document.getElementById('id_country');
const options=selectEl.options;
for(设i=0,len=options.length;i
从一个完全无关的角度讲,像这样的国家下拉列表总是让我发笑。您预计奥兰群岛和阿富汗会有多少客户?:)IE的版本可能会有所帮助这对我在IE9中使用IE7和IE8浏览器模式很有用(不幸的是,我没有安装旧浏览器的实际副本)。你所做的似乎完全正确。较旧的浏览器可能希望您在选项上循环,并将匹配选项的选定值设置为布尔值trueSapph和mplungjan,您是对的。它在InternetExplorer中确实工作得很好。问题完全不同:在InternetExplorer中,我有不同的语言设置。GoogleMaps使用地理编码api以特定于语言环境的语言返回国家名称。当我发出API请求时,我必须设置正确的语言。这完全是一种倒退的方式。您希望的意思是“在选项上循环并将匹配选项的选定值设置为布尔值true”@mplungjan:afshin说的“将选项的“selected”属性设置为字符串“selected”是正确的。它是这样做的:
options[i].setAttribute(“selected”、“selected”)。然而,这样做是不寻常的。@RoT它似乎可以工作,但是Fx4告诉我通过HTML选择的和setAttibute one has selected=“selected”它在IE中可以工作,如果(选项[I].value==country){options[I].selected=true;}
但只是为了取悦真正的老浏览器
function setCountryOption(country) {
  const selectEl = document.getElementById('id_country');
  const options = selectEl.options;

  for (let i = 0, len = options.length; i < len; i++) {
    if (options[i].value == country) {
      options[i].setAttribute('selected', 'selected');
    }
  }
}