通过 JavaScript 将 & 字符代码添加到 HTML

Joh*_*etz 2 html javascript

我正在尝试×使用 javascript将时间符号添加到 HTML 模板。不幸的是,HTML 将 & 字符代码作为字符串读取。我怎样才能解决这个问题?

HTML:

<button id='b'>Add Symbol</button>
<div>&times;</div>
<div id='container'></div>
Run Code Online (Sandbox Code Playgroud)

JS:

document.getElementById('b').onclick = addSymbol;
function addSymbol() {
    var pTag = document.createElement('p');
  var pTagContent = document.createTextNode('&times;');
  pTag.appendChild(pTagContent);

  var container = document.getElementById('container');
  container.appendChild(pTag);
}
Run Code Online (Sandbox Code Playgroud)

https://jsfiddle.net/a2w1w0n3/

I w*_*ce. 8

当您使用createTextNodejavascript 不解析 html 或实体时,您需要使用innerHTML它来显示实体。

var pTag = document.createElement('p');
pTag.innerHTML = '&times;';
Run Code Online (Sandbox Code Playgroud)