jquery – .text()和.html()与转义的<和>字符之间的差异

前端之家收集整理的这篇文章主要介绍了jquery – .text()和.html()与转义的<和>字符之间的差异前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
给出以下 HTML片段:
<p id="para">hello &lt;world&gt;</p>

jQuery .text().html()方法将返回不同的值…

var text = $('#para').text(); // gives 'hello <world>'
var html = $('#para').html(); // gives 'hello &lt;world&gt;'

jQuery文档说明

@H_403_10@

The result of the .text() method is a string containing the combined text of all matched elements.

和…

@H_403_10@

In an HTML document,we can use .html() to get the contents of any element. If the selector expression matches more than one element,only the first one’s HTML content is returned.

但是与& lt和& gt;似乎没有记录在任何地方.

有人可以评论这个差异的理由吗?

编辑

更多的调查表明,值.text()和.html()分别匹配来自本机JavaScript innerText和innerHTML调用的值(当jQuery选择器至少返回一个元素时).再次,这并没有反映在jQuery文档中,所以我不能100%肯定这个观察是否符合所有情况.通过jQuery source阅读可以看出,这不是实际发生的情况.

解决方法

这是按照相应的javascript方法textContent和innerHTML.
>> console.log(document.getElementsByTagName('p')[0].textContent);
hello <world>

>> console.log(document.getElementsByTagName('p')[0].innerHTML);
hello &lt;world&gt;

猜你在找的jQuery相关文章