代码之家  ›  专栏  ›  技术社区  ›  Christopher Mahan

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

  •  1
  • Christopher Mahan  · 技术社区  · 14 年前

    给定下面的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数字,而是选择中的值。

    1 回复  |  直到 14 年前
        1
  •  2
  •   Tim Down    14 年前

    精选的 options 属性不保证包含与每个选项的值对应的属性。大多数浏览器(不是IE)将其实现为 HTMLOptionsCollection ,这是令人困惑的指定:dom规范和 MDC 两者似乎都表明 选项 应与选项元素的名称和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];
    }