简体   繁体   English

如何使用带有 textContent 的实体

[英]How to use an entity with textContent

I want to set the text content of an element using JavaScript.我想使用 JavaScript 设置元素的文本内容。 If I do this:如果我这样做:

var el = document.getElementById('my-element')
el.textContent = '×' 

The result is:结果是:

<div id="my-element">&amp;times;</div>

I tried using \\& instead but that had no effect.我尝试使用\\&代替,但没有效果。 How can I actually insert the entity into the text content?如何将实体实际插入文本内容中?

textContent will not parse the HTML for you. textContent不会为您解析 HTML。

Use innerHTML instead if you want the specified text to be parsed.如果您希望解析指定的文本,请改用innerHTML

 var el = document.getElementById('my-element') el.textContent = '&times;' var el2 = document.getElementById('my-element2') el2.innerHTML = '&times;'
 <div id="my-element"></div> <div id="my-element2"></div>

As answered by others, you can't use HTML entities with textContent ,正如其他人所回答的那样,您不能将 HTML 实体与textContent
and there is no need to do so .并且没有必要这样做
Just use the character directly:直接使用字符即可:

 el.textContent= "7 × 6 = 42";   // 7 &times; 6 = 42
 el.textContent= "💡 🙂";

Make sure your files are encoded with <meta charset=UTF-8> .确保您的文件使用<meta charset=UTF-8>编码。 That's a requirement these days anyway.无论如何,这是当今的要求。

Some HTML entities are problematic to handle directly, eg spaces like &thinsp;一些 HTML 实体直接处理有问题,例如像&thinsp;这样的&thinsp; or &nbsp;&nbsp; . . Here you can use a hexadecimal Unicode escape sequence.在这里您可以使用十六进制 Unicode 转义序列。
"NO-BREAK SPACE [NBSP]" is codepoint U+00A0. “NO-BREAK SPACE [NBSP]”是代码点 U+00A0。 As Javascript string just write \\xa0 or .作为 Javascript 字符串,只需写\\xa0

el.textContent= "foo\xa0bar";
el.textContent= "foo\u00a0bar";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM