How do I dynamically create an <option> in JavaScript that contains an HTML entity (— … «)?

自闭症网瘾萝莉.ら 提交于 2019-11-30 02:56:15

问题


I'd like to add an <option> element to a <select> element where the <option> element's text contains an HTML entity: &mdash;

In HTML, the code would look like this:

<select name="test" id="test">
    <option value="">&mdash; Select One &mdash;</option>
</select>

My JavaScript code looks like this:

function selectOne() {
  var e = document.getElementById('test');
  e.options[0] = new Option('&mdash; Select One &mdash;', '');
}

However, as you will see if you test this, the &mdash; becomes escaped. I had the same outcome when I tried:

e.options[o].text = '&mdash; Select One &mdash;';

(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.)


回答1:


I just realized I could use a Unicode JavaScript escape:

e.options[0] = new Option('\u2014 Select One \u2014', '');



回答2:


You don't need to escape the entity - it works like this:

function selectOne() {
      var e = document.getElementById('test');
      e.options[0] = new Option('— Select One —', '');
}



回答3:


text property doesn't get unescaped, as it is meant to be taken literally. If you use innerHTML, the entities get converted to corresponding characters.

e.options[o].innerHTML = '&mdash; Select One &mdash;';


来源:https://stackoverflow.com/questions/425234/how-do-i-dynamically-create-an-option-in-javascript-that-contains-an-html-enti

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!