javascript - 无法在 IE8 中使用 javascript 在选择下拉列表中设置选择

标签 javascript internet-explorer-8

给定以下 javascript 函数,

function switch_plug_drop_down(plug_id) {
      selector = document.getElementById('group_1');
      if (plug_id == "1") {selector.options['product_253'].selected = true;}
      if (plug_id == "2") {selector.options['product_217'].selected = true;}
      if (plug_id == "3") {selector.options['product_254'].selected = true;}
      if (plug_id == "4") {selector.options['product_255'].selected = true;}
      if (plug_id == "5") {selector.options['product_256'].selected = true;}
  }

和下面的 HTML 选择元素(由 cs-cart 生成)

<select name="product_data[245][configuration][1]" id="group_1" onchange="fn_check_exceptions(245);fn_check_compatibilities(1,'select','S');"> 
    <option id="product_255" value="255"  >Power Adapter Plug Choice AUS<span class="price"></span></option> 
    <option id="product_217" value="217"  >Power Adapter Plug Choice EURO<span class="price"></span></option> 
    <option id="product_256" value="256"  >Power Adapter Plug Choice JAPAN<span class="price"></span></option> 
    <option id="product_254" value="254"  >Power Adapter Plug Choice UK<span class="price"></span></option> 
    <option id="product_253" value="253" selected="selected"} >Power Adapter Plug Choice USA / Canada<span class="price"></span></option> 
</select> 

这在 FF 3.6.8、Chrome 5.0.375 中工作正常,但在 IE 8(浏览器模式 8,文档模式 IE8 标准)中失败

我在 IE 8 的 javascript 调试器中遇到错误:

'selector.options.product_217' is null or not an object

这对应上面js代码中的selector.options['product_217'].selected = true;

另外,jQuery 1.3.n 在网站上并且工作正常。

有人知道发生了什么以及如何解决它吗?

更新:

我实现了 Tim 的解决方案,但自动加载了值:

selector = document.getElementById('group_1');
for (var i = 0; i < selector.children.length; ++i) {
    var child = selector.children[i];
    if (child.tagName == 'OPTION') optionIndicesByPlugId[child.value]=''+i;
}

(此代码来自this SO question's first answer)

并且传递给 switch_plug_drop_down 函数的 plug_id 不再是 1-5 的数字,而是选择中的值。

最佳答案

不保证选择的 options 属性包含与每个选项的值相对应的属性。大多数浏览器(不是 IE)将其实现为 HTMLOptionsCollection ,这是令人困惑的指定:DOM 规范和 MDC两者似乎都表明 options 的非数字属性应该对应于选项元素的名称和 ID。因此,最跨浏览器的方法是改用数字属性。

设置当前选择哪个选项的最简单方法是使用选择的 selectedIndex 属性:

var optionIndicesByPlugId = {
    "1": 4,
    "2": 1,
    "3": 3,
    "4": 0,
    "5": 2
};

function switch_plug_drop_down(plug_id) {
    var selector = document.getElementById('group_1');
    selector.selectedIndex = optionIndicesByPlugId[plug_id];
}

关于javascript - 无法在 IE8 中使用 javascript 在选择下拉列表中设置选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3588763/

相关文章:

javascript - .隐藏与子元素无关的任何点击操作

html - CSS DIV 悬停在 Internet Explorer 8 中不起作用

CSS 下拉菜单在 IE8 中不起作用

css - word-wrap:break-word 在 IE8 中不工作

javascript - Internet Explorer 8 原型(prototype)和 XMLHttpRequest

css - 几乎所有的 Bootstrap 样式在 IE8 中都不起作用。在 chrome 和 firefox 中工作正常

Javascript使用php中的switch case从mysql数据库检索数据

javascript - 如何对D3中的节点进行排序,以使连接路径清晰明了?

javascript - 单击按钮即可洗牌阵列

javascript - 2个事件处理程序分配之间的区别