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>');
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标记之间的实际文本。例如,p标记之间的段落文本。值得注意的是,它将为您提供使用$选择器所瞄准的元素中的所有文本,以及所选元素的子元素中的所有文本。如果你在body元素中有多个带有文本的p标签,你执行$(body).text(),你将获得所有段落的所有文本。(只有文本,而不是p标签本身。)
.html()将为您提供文本和标记。$(body).html()会给你整个HTML页面
.val()适用于具有value属性的元素,例如input。 输入不包含文本或HTML,因此.text()和. HTML()对于输入元素都将为空。
其他回答
$('.div'). HTML (val)将设置所有选定元素的HTML值,$('.div').text(val)将设置所有选定元素的文本值。
jQuery.text()的API文档
jQuery.html()的API文档
我猜它们分别对应于node# textContent和Element#innerHTML。(Gecko DOM参考)。
基本上,$("#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).
(如有必要请更新,这个答案是Wiki)
子问题:当只有文本时,.text()或.html()哪个更快?
答案:.html()更快!请看这里所有问题的“行为测试包”。
所以,总之,如果你只有“一个文本”,使用html()方法。
注:说不通吗?请记住,.html()函数只是. innerhtml的包装器,但在.text()函数中,jQuery添加了一个“实体过滤器”,这个过滤器自然会消耗时间。
好吧,如果你真的想要性能……使用纯Javascript访问nodeValue属性的直接文本替换。 基准测试结论:
jQuery的.html()比.text()快2倍。 纯JS的. innerhtml比.html()快3倍。 纯JS的. nodevalue比.html()快50倍,比.text()快100倍,比. innerhtml快20倍。
PS: . textcontent属性是DOM-Level-3引入的,. nodevalue是DOM-Level-2并且更快(!)
查看完整的基准测试:
// Using jQuery:
simplecron.restart(); for (var i=1; i<3000; i++)
$("#work").html('BENCHMARK WORK');
var ht = simplecron.duration();
simplecron.restart(); for (var i=1; i<3000; i++)
$("#work").text('BENCHMARK WORK');
alert("JQuery (3000x): \nhtml="+ht+"\ntext="+simplecron.duration());
// Using pure JavaScript only:
simplecron.restart(); for (var i=1; i<3000; i++)
document.getElementById('work').innerHTML = 'BENCHMARK WORK';
ht = simplecron.duration();
simplecron.restart(); for (var i=1; i<3000; i++)
document.getElementById('work').nodeValue = 'BENCHMARK WORK';
alert("Pure JS (3000x):\ninnerHTML="+ht+"\nnodeValue="+simplecron.duration());
不同的是.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代码时,请使用text()。
从技术上讲,第二个示例生成:
<a href="example.html">Link</a><b>hello</b>
它将在浏览器中呈现为:
<a href="example.html">Link</a><b>hello</b>
您的第一个示例将呈现为一个实际的链接和一些粗体文本。