无法在IE8中使用javascript选择下拉列表中的选择

时间:2010-08-27 23:30:32

标签: 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 select元素(由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数字,而是select中的值。

1 个答案:

答案 0 :(得分:2)

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

设置当前选择的选项的最简单方法是使用select的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];
}