【问题标题】:InnerHTML IE 8 doesn't work properly? Resetting formInnerHTML IE 8 不能正常工作?重置表格
【发布时间】:2011-02-03 22:09:34
【问题描述】:

是的,这在 FF 和 Chrome 中有效,但由于某种原因在 IE 8 中无效。我正在使用单选按钮来清除表单的一部分。该部分是一个选择框,但我不想要将该区域留空 - 相反,我想将其重置为页面加载时的状态。目前 IE8 只给我一个空的小选择框。

HTML:

<select id="city_select" disabled="true" name="location_id" onchange="show_search_button();"><option selected>Select your city</option> </select>

Javascript:

document.getElementById('city_select').innerHTML = "<option selected>Select your city</option>";

我也尝试在 javascript 中使用 location_id 而不是 city_select 但无济于事.. innerText 和 innerContent 也不起作用.. 虽然 inner.HTML 在 IE8 中适用于早期功能,但这并不是试图将 innerHTML 放入表单。有谁知道为什么这适用于 Chrome 和 FF 而不是 IE8?有没有解决办法?任何帮助表示感谢!

【问题讨论】:

    标签: forms select internet-explorer-8 innerhtml


    【解决方案1】:

    试试这个:

    document.getElementById('city_select').options.length = 0;
    

    然后创建一个新选项并将其推送到选择的选项数组中。选项有点棘手,与其他标记不同。

    已编辑以显示如何创建选项:

    var sel = document.getElementById('city_select').options.length = 0;
    var opt = document.createElement('option');
    opt.value = "Select Your City";
    sel.options.push(opt);
    sel.selectedIndex = 0;
    

    【讨论】:

    • 感谢您的回复!我想当它不是凌晨 2.30 时我需要重新阅读它,不太确定如何做第二部分 - 但也许是因为我半睡着了!无论如何,干杯,希望这有效:)
    • 感谢您的帮助!不幸的是,在用上面的代码替换了我的代码行之后——firefox、chrome 或 IE 现在都不能工作(它们都只显示一个空的选择框).. 这是一个正确的令人头疼的问题。不过再次感谢..
    • 知道如何做到这一点仍然很有趣 - 但我没有重置选择框,而是完全隐藏了选择框(默认和重置时),效果很好: ) 为你的时间干杯:)
    • 代替 sel.options.push(opt),试试 sel.options[0] = opt.
    【解决方案2】:

    应该有 4 种方式将新选项分配给选择元素。有些适用于某些场景,有些适用于其他场景。看这里-How to Add options to <SELECT>, in IE Windows Mobile 5

    对我来说,Robusto 的解决方案没有奏效,原因有以下三个:

    1) 将第一行中的sel 变量分配给document.getElementById('city_select').options.length = 0;,而不是简单地持有选择元素(供稍后在第 4 行和第 5 行使用)然后删除下一行中的选项,如下所示:

    var sel = document.getElementById('city_select');
    sel.options.length = 0;
    

    2) 第 4 行 sel.options.push(opt)(或后来建议的 sel.options[0] = opt)抛出 Object 不支持此属性或方法 错误。而是使用这个:

    sel.appendChild(opt);
    

    3) 除了为选项分配值之外,您还必须分配要显示的文本。你这样做:

    opt.innerText = "Select Your City - displayed";
    

    因此,总结一下:

    var sel = document.getElementById('city_select');
    sel.options.length = 0;
    var opt = document.createElement('option');
    opt.value = "Select Your City";
    opt.innerText = "Select Your City - displayed";
    sel.appendChild(opt);
    sel.selectedIndex = 0;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-04
      • 2018-02-12
      • 1970-01-01
      • 2014-10-15
      • 1970-01-01
      相关资源
      最近更新 更多