如何动态创建<选项>在JavaScript中包含HTML实体( - ...«)? [英] How do I dynamically create an <option> in JavaScript that contains an HTML entity (— ... «)?
问题描述
我想添加<选项>元素到< select>元素所在的<选项> element的文本包含一个HTML实体:& mdash;
I'd like to add an <option> element to a <select> element where the <option> element's text contains an HTML entity: —
在HTML中,代码如下所示:
In HTML, the code would look like this:
<select name="test" id="test">
<option value="">— Select One —</option>
</select>
我的JavaScript代码如下所示:
My JavaScript code looks like this:
function selectOne() {
var e = document.getElementById('test');
e.options[0] = new Option('— Select One —', '');
}
但是,正如您将看到的,如果您测试这个,那么& mdash;变得逃脱。我尝试时得到的结果相同:
However, as you will see if you test this, the — becomes escaped. I had the same outcome when I tried:
e.options[o].text = '— Select One —';
(观察到的行为是在互联网资源管理器7中...没有使用Firefox,Safari等进行测试。 - Internet Explorer 7是我目前唯一需要的浏览器。)
(Observed behavior was in Internet Explorer 7 ... did not test with Firefox, Safari, etc. -- Internet Explorer 7 is the only browser I need at the moment.)
推荐答案
我刚才意识到我可以使用Unicode JavaScript转义:
I just realized I could use a Unicode JavaScript escape:
e.options[0] = new Option('\u2014 Select One \u2014', '');
这篇关于如何动态创建<选项>在JavaScript中包含HTML实体( - ...«)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!