gpt4 book ai didi

javascript - 使用 textContent 将图标字体代码(如 )添加到 DOM 时无效

转载 作者:行者123 更新时间:2023-12-01 02:02:08 65 4
gpt4 key购买 nike

我在我的网站中使用 google iconfonts。
通常,HTML 中的代码是这样的:

<i class="material-icons">&#xE87C;</i>

页面上会显示一个“时间”图标: the icon will display

但是现在我想使用appendChild()方法向DOM添加一个图标。代码是:

var my_element = document.getElementById("icon-div");

// create a i tag
var i = document.createElement("i");
i.className = "material-icons";
i.textContent = "&#xe192;";

// append the tag to my_element
my_element.appendChild(i);
<html>
<head>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>

<body>
<!--it should be-->
<i class="material-icons">&#xe192;</i>

<!--add it by using appendChild method-->
<div id="icon-div">
</div>
</body>
</html>

当我检查<i>时(div中的那个)在浏览器控制台中,其文本内容为 "&#xe192;" ,其innerHTML为"&amp;#xe192;" ;

那么当我动态向 DOM 添加图标时如何获取图标。

最佳答案

使用innerHTML而不是textContent:

var my_element = document.getElementById("icon-div");

// create a i tag
var i = document.createElement("i");
i.className = "material-icons";
i.innerHTML = "&#xe192;";

// append the tag to my_element
my_element.appendChild(i);
<html>
<head>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>

<body>
<!--it should be-->
<i class="material-icons">&#xe192;</i>

<!--add it by using appendChild method-->
<div id="icon-div">
</div>
</body>
</html>

textContent 假设您正在插入文本;所以它会转义输入,这样它就不会显示为 HTML。您希望它显示为 HTML。

关于性能:textContentsignificantly fasterinnerHTML 更重要,因为浏览器不需要解析输入,所以尽可能选择 textContent 并不是一个坏主意 - 但在这种情况下,您实际上需要它解析发生,因此有必要承受较小的性能影响。在大多数现实情况下,差异可以忽略不计,您必须执行数万次 DOM 插入,差异才会明显。

关于javascript - 使用 textContent 将图标字体代码(如 )添加到 DOM 时无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50469117/

65 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com