.text()和.html()之间的区别,其中转义了<和>人物 [英] Differences between .text() and .html() with escaped < and > characters

查看:96
本文介绍了.text()和.html()之间的区别,其中转义了<和>人物的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下HTML片段:

Given the following HTML fragment:

<p id="para">hello &lt;world&gt;</p>

jQuery .text()

The jQuery .text() and .html() methods will return different values...

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

jQuery文档说明

The jQuery documentation states

.text()方法的结果是一个字符串,其中包含所有匹配元素的组合文本.

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

和...

在HTML文档中,我们可以使用.html()来获取任何元素的内容.如果选择器表达式匹配多个元素,则仅返回第一个的HTML内容.

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;的这种特定区别似乎在任何地方都没有记录.

But this specific difference with &lt; and &gt; doesn't seem to be documented anywhere.

任何人都可以评论这种差异的理由吗?

Can anyone comment on the rationale for this difference?

进一步的研究表明,值.text().html()分别与本地JavaScript innerTextinnerHTML调用中的值匹配(至少当jQuery选择器返回单个元素时).同样,这没有反映在jQuery文档中,因此我不能100%地确定这种观察是否在所有情况下都适用.仔细阅读 jQuery来源可以发现,这并不是实际情况.罩.

A little more investigation suggests that the values .text() and .html() match those from the native JavaScript innerText and innerHTML calls respectively (when the jQuery selector has returned a single element, at least). Again, this is not reflected in the jQuery documentation so I am not 100% sure if this observation holds true in all scenarios. Reading through the jQuery source reveals that this isn't what's actually going on under the hood.

推荐答案

这符合相应的JavaScript方法textContentinnerHTML.

This is in accordance with the corresponding JavaScript methods textContent and innerHTML.

>> console.log(document.getElementsByTagName('p')[0].textContent);
hello <world>

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

这篇关于.text()和.html()之间的区别,其中转义了&lt;和&gt;人物的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆