【问题标题】:Why does IE 11 javascript strips spaces in value method?为什么 IE 11 javascript 在值方法中去除空格?
【发布时间】:2014-07-02 15:52:35
【问题描述】:

在选择标签中具有“Ø-&”的选件值时?

HTML:

<select id="companies">
       <option>ø- &</option>
       <option>ø- &amp;</option>
       <option>&oslash;- &amp;</option>
</select>
<button onclick="javascript:alert(document.getElementById('companies').value);">TEST</button>

JSFiddle:http://jsfiddle.net/aK35t/14/

【问题讨论】:

    标签: javascript html internet-explorer-11


    【解决方案1】:

    这仅仅是因为您正在读取选项的值 - 但值中的空格并不是真正有效的。相反,您想阅读 文本

    document.getElementById('companies')
    .options[document.getElementById('companies').selectedIndex].text
    

    但是,无论如何,您都不应该依赖自动“文本到价值”。如果您手动设置选项的值,它也可以与您的原始代码一起正常工作:

    <select id="companies">
        <option value="ø- &amp;">ø- &amp;</option>
    </select>
    <button onclick="alert(document.getElementById('companies').value);">GET</button>
    

    无论如何,您很可能在选项值中有一些 ID - 因此,如果您想在 javascript 中获取文本,请使用上面的 sn-p 方式(或使用 jQuery 的 text())。

    【讨论】:

    • 使用value 属性确实可以解决问题,但空格 有效的,并且它们被剥离是 IE 11 中的一个错误(例如在 IE 10 中不存在)关闭(当从其内容构造optionvalue 属性时,在没有value 属性的情况下)。
    • IE 11 错误似乎取决于option 值中是否存在非ASCII 数据,请参阅错误报告IE11 option.value returns mangled data when value contains HTML extended characters
    • @JukkaK.Korpela 这不是那么简单。正如 HTML5 规范所说,The text IDL attribute, on getting, must return the value of the textContent IDL attribute on the element, with leading and trailing whitespace stripped, and with any sequences of two or more space characters replaced by a single U+0020 SPACE character. On setting, it must act as if the textContent IDL attribute on the element had been set to the new value. 所以它可能是一个错误,但比看起来更复杂的错误(例如,使用abc def 保留了空间,č&amp;nbsp;-&amp;amp; 也是如此)。这很棘手。
    【解决方案2】:

    问题似乎在于您的多字节字符(ø,æ)。或许可以强制网页使用utf8编码?

    Jquery 以某种方式解决了这个问题。

    function getCompaniesValue() {
        alert($("#companies").val());
    }
    

    给出正确的结果。

    【讨论】:

    • 已尝试使用不起作用的 utf8。我尝试过使用不起作用的 jquery 1.7.1。你用的是什么版本?
    • @kasperxb:使用 Jquery 1.11。小提琴更新:jsfiddle.net/aK35t/15
    【解决方案3】:

    我没有 IE 11 来测试它,但对我来说这似乎是一个编码问题。您应该尝试使用正确的 HTML 实体来做到这一点:

    <select id="companies">
        <option>&oslash;- &amp;</option>
        <option>&oslash;- &</option>
    </select>
    <button onclick="javascript:alert(document.getElementById('companies').value);">TEST</button>
    

    【讨论】:

    • 用 ø 试过但它不工作!更新了 jsfiddle。
    猜你喜欢
    • 1970-01-01
    • 2016-08-13
    • 2014-06-23
    • 1970-01-01
    • 2020-01-18
    • 2011-09-20
    • 1970-01-01
    • 2013-03-30
    相关资源
    最近更新 更多