给定下面的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
这相当于
selector.options['product_217'].selected = true;
在上面的JS代码中。
另外,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
函数不再是1-5数字,而是选择中的值。