ada*_*ryk 119 javascript dom innerhtml nodevalue
我使用普通的js来改变标签元素的内部文本,我不确定我应该使用innerHTML或nodeValue或textContent.我不需要创建新节点或更改HTML元素或任何东西 - 只需替换文本.这是代码的示例:
var myLabel = document.getElementById("#someLabel");
myLabel.innerHTML = "Some new label text!"; // this works
myLabel.firstChild.nodeValue = "Some new label text!"; // this also works.
myLabel.textContent = "Some new label text!"; // this also works.
Run Code Online (Sandbox Code Playgroud)
我查看了jQuery源代码,它使用了nodeValue一次,但是innerHTML和textContent几次.然后我发现这个jsperf测试表明firstChild.nodeValue明显更快.至少这就是我所说的意思.
如果firstChild.nodeValue快得多,那捕获的是什么?它没有得到广泛支持吗?还有其他问题吗?
pet*_*ldi 139
MDN上textContent/innerText/innerHTML之间的差异.
还有一个关于innerText/nodeValue的Stackoverflow答案.
摘要
innerText根据caniuse, FireFox 45之前在firefox中不存在,但现在所有主流浏览器都支持.
Bri*_*ian 53
.textContent输出text/plain时的.innerHTML输出text/html.
快速举例:
var example = document.getElementById('exampleId');
example.textContent = '<a href="https://google.com">google</a>';
输出:<a href="http://google.com">谷歌</a>
example.innerHTML = '<a href="https://google.com">google</a>';
输出:谷歌
您可以从第一个示例中看到,text/plain浏览器未解析类型的输出并导致显示完整内容.该类型的输出text/html告诉浏览器在显示它之前解析它.
MDN innerHTML,MDN textContent,MDN nodeValue
我熟悉并使用的两个是innerHTML和textContent.
当我只想更改段落或标题的文本时,我使用textContent:
var heading = document.getElementById('heading')
var paragraph = document.getElementById('paragraph')
setTimeout(function () {
heading.textContent = 'My New Title!'
paragraph.textContent = 'My second <em>six word</em> story.'
}, 2000)Run Code Online (Sandbox Code Playgroud)
em { font-style: italic; }Run Code Online (Sandbox Code Playgroud)
<h1 id="heading">My Title</h1>
<p id="paragraph">My six word story right here.</p>Run Code Online (Sandbox Code Playgroud)
因此,textContent只是更改了文本,但它不解析HTML,因为我们可以从结果中的纯文本中看到的标签中看出.
如果我们想解析HTML,我们使用innerHTML,如下所示:
var heading = document.getElementById('heading')
var paragraph = document.getElementById('paragraph')
setTimeout(function () {
heading.innerHTML = 'My <em>New</em> Title!'
paragraph.innerHTML = 'My second <em>six word</em> story.'
}, 2000)Run Code Online (Sandbox Code Playgroud)
em { font-style: italic; }Run Code Online (Sandbox Code Playgroud)
<h1 id="heading">My Title</h1>
<p id="paragraph">My six word story right here.</p>Run Code Online (Sandbox Code Playgroud)
因此,第二个示例将我分配给DOM元素的innerHTML属性的字符串解析为HTML.
这很棒,而且是一个很大的安全漏洞:)
(如果你想了解安全性,请查找XSS)
| 归档时间: |
|
| 查看次数: |
68339 次 |
| 最近记录: |