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>');
当前回答
**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();
});
其他回答
我认为区别在于插入html标签 在text()中你的HTML标签没有函数
$('#output').html('You are registered'+'<br>' +' '
+ 'Mister'+' ' + name+' ' + sourname ); }
输出:
You are registered <br> Mister name sourname
用html()替换text()
输出
You are registered
Mister name sourname
那么标签<br>在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).
实际上,两者看起来有点相似,但却有很大的不同,这取决于你的用法或你想要达到的目的,
使用地点:
使用. HTML()对含有HTML元素的容器进行操作。 使用.text()修改元素的文本,通常有单独的打开和 结束标签
不使用的地方:
.text()方法不能用于表单输入或脚本。 .val()用于输入或文本区域元素。 .html()表示脚本元素的值。 从.text()中获取html内容将把html标记转换为html实体。
的区别:
.text()可以在XML和HTML文档中使用。 . HTML()仅用于HTML文档。
检查jsfiddle上的这个示例,以查看操作上的差异
例子
(如有必要请更新,这个答案是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());