我正在尝试×使用 javascript将时间符号添加到 HTML 模板。不幸的是,HTML 将 & 字符代码作为字符串读取。我怎样才能解决这个问题?
HTML:
<button id='b'>Add Symbol</button>
<div>×</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('×');
pTag.appendChild(pTagContent);
var container = document.getElementById('container');
container.appendChild(pTag);
}
Run Code Online (Sandbox Code Playgroud)
当您使用createTextNodejavascript 不解析 html 或实体时,您需要使用innerHTML它来显示实体。
var pTag = document.createElement('p');
pTag.innerHTML = '×';
Run Code Online (Sandbox Code Playgroud)