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。当您想要插入对查看页面的人可见的HTML代码时,请使用text()。
从技术上讲,第二个示例生成:
<a href="example.html">Link</a><b>hello</b>
它将在浏览器中呈现为:
<a href="example.html">Link</a><b>hello</b>
您的第一个示例将呈现为一个实际的链接和一些粗体文本。
其他回答
var v = "全名";
$("#div").html(v); //display as "全名"
$("#div").text(v); //display as "全名"
text()——该方法设置或返回所选元素的文本内容。 html()——该方法设置或返回所选元素的内容。 参考示例:https://www.tutorialspoint.com/online_jquery_editor.php
第一个例子实际上将HTML嵌入到div中,而第二个例子将转义文本,方法是将与元素相关的字符替换为相应的字符实体,以便按字面意思显示(即HTML将被显示而不呈现)。
**difference between text()&& html() && val()...?
#Html code..
<select id="d">
<option>Hello</option>
<option>Welcome</option>
</select>
# jquery code..
$(document).ready(function(){
$("#d").html();
$("#d").text();
$("#d").val();
});
(如有必要请更新,这个答案是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());
当您打算将值显示为简单文本时,请使用.text(…)。
当您打算将值显示为html格式的文本(或html内容)时,使用.html(…)。
当你不确定你的文本(例如来自输入控件)不包含在HTML中有特殊意义的字符/标记时,你一定要使用.text(…)。这是非常重要的,因为这可能会导致文本不能正常显示,但也可能导致不需要的JS脚本片段(例如来自另一个用户输入)被激活。