2010-08-27 61 views
1

鉴于以下JavaScript功能,无法设置在与JavaScript选择下拉选择在IE8

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-车产生)

<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是在网站上,工作正常。

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

UPDATE:

我实现了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; 
} 

,并传递给switch_plug_drop_down的plug_id(此代码this SO question's first answer来)函数不再是1-5数字,而是select中的值。

回答

2

选择的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]; 
} 
+0

嗯。它可能与下拉式中的id与value相关......现在正在调查。 更新:不。 – 2010-08-27 23:45:30

+0

更新了我的答案。 – 2010-08-27 23:47:39

+0

看到了。我正在看它... – 2010-08-27 23:54:25