给出以下
HTML片段:
<p id="para">hello <world></p>
jQuery .text()
和.html()
方法将返回不同的值…
var text = $('#para').text(); // gives 'hello <world>' var html = $('#para').html(); // gives 'hello <world>'
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 <world>