【问题标题】:Appending select options - IE problem/solution cause other browser issues附加选择选项 - IE 问题/解决方案导致其他浏览器问题
【发布时间】:2010-10-18 00:27:27
【问题描述】:

我有一个 <select>,根据之前的选项,它由一个带有一堆 <option> 值的 var 填充。

当然,因为 IE 不能与 innerHTML 一起工作,我必须将此模板附加到 <select>,它现在在 IE 中工作得很好。但是我现在需要一种方法来清除先前搜索中的选择选项,并在 FF 中阻止它下拉到列表中的最后一个 <option>

【问题讨论】:

  • 我有一个依赖于先前选项的变量填充了一个带有一堆值的变量。 -- 那个“句子”是无法辨认的

标签: javascript internet-explorer select innerhtml


【解决方案1】:

只需使用 innerHTML 重写整个选择块,这总是有效的。

【讨论】:

    【解决方案2】:

    <select> 中清除选项的万无一失的方法:

    while( select_control.length > 0 )
         select_control.options[0] = null
    

    如果您使用select_control.length = 0,某些浏览器会清除列表,但我发现这不可靠。

    万无一失的插入选项:

    var new_option = new Option(text, value)
    try {
        select_control.add(new_option, select_control.options[0])
    } catch(e) {
        select_control.add(new_option, 0)
    }
    

    0 是您之前想要的项目的索引。要将其添加到末尾,请改为:

    select_control.options[select_control.length] = new_option
    

    如果您想通过指定现有选项的索引替换特定项目,这也将起作用。

    【讨论】:

    • 这是一些很好的信息,但是我发现循环运行 new Option 100 次会在某些计算机上锁定 IE。
    • 好吧,我没遇到过那个bug!我通常只想添加一两个。如果我要重新填充整个列表,我通常会渲染每个列表并使用 CSS display 属性来显示正确的列表。 (当然,服务器端也必须知道查看正确的表单元素。)
    【解决方案3】:

    很好地使用 YUI3:

        node.setContent(template); //removes old children, sets new template as content.
        node.set('selectedIndex', 0); //forces FF to select the first one
    

    用正确的方法编辑。

    【讨论】:

      猜你喜欢
      • 2012-12-21
      • 2022-09-29
      • 1970-01-01
      • 1970-01-01
      • 2014-04-05
      • 2012-02-07
      • 2014-09-19
      • 2016-04-20
      • 2013-04-04
      相关资源
      最近更新 更多