jQuery中的text()和html()函数有什么区别?

$("#div").html('<a href="example.html">Link</a><b>hello</b>');

vs

$("#div").text('<a href="example.html">Link</a><b>hello</b>');

当前回答

text函数将值设置或检索为纯文本,否则,HTML函数将值设置或检索为HTML标记,以更改或修改该值。 如果你只想改变内容,那么使用text()。但是如果你需要改变标记,那么你必须使用hmtl()。

这对我来说是个愚蠢的答案,别介意。

其他回答

不同的是.html()评估为html, .text()评估为文本。 考虑一个html块 超文本标记语言

<div id="mydiv">
<div class="mydiv">
    This is a div container
    <ul>
      <li><a href="#">Link 1</a></li>
      <li><a href="#">Link 2</a></li>
    </ul>
    a text after ul
</div>
</div>

JS

var out1 = $('#mydiv').html();
var out2 = $('#mydiv').text();
console.log(out1) // This output all the html tag
console.log(out2) // This is output just the text 'This is a div container Link 1 Link 2 a text after ul'

插图来自这个链接http://api.jquery.com/text/

当您打算将值显示为简单文本时,请使用.text(…)。

当您打算将值显示为html格式的文本(或html内容)时,使用.html(…)。

当你不确定你的文本(例如来自输入控件)不包含在HTML中有特殊意义的字符/标记时,你一定要使用.text(…)。这是非常重要的,因为这可能会导致文本不能正常显示,但也可能导致不需要的JS脚本片段(例如来自另一个用户输入)被激活。

基本上,$("#div").html使用element。innerHTML设置内容,$(“#div”)。text(可能)使用element.textContent。

http://docs.jquery.com/Attributes/html:

Set the html contents of every matched element

http://docs.jquery.com/Attributes/text:

Similar to html(), but escapes HTML (replace "<" and ">" with their HTML 
entities).

第一个例子实际上将HTML嵌入到div中,而第二个例子将转义文本,方法是将与元素相关的字符替换为相应的字符实体,以便按字面意思显示(即HTML将被显示而不呈现)。

var v = "&#x5168;&#x540D;";
$("#div").html(v); //display as "全名"
$("#div").text(v); //display as "&#x5168;&#x540D;"

text()——该方法设置或返回所选元素的文本内容。 html()——该方法设置或返回所选元素的内容。 参考示例:https://www.tutorialspoint.com/online_jquery_editor.php