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>');
当前回答
不同的是.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标记之间的实际文本。例如,p标记之间的段落文本。值得注意的是,它将为您提供使用$选择器所瞄准的元素中的所有文本,以及所选元素的子元素中的所有文本。如果你在body元素中有多个带有文本的p标签,你执行$(body).text(),你将获得所有段落的所有文本。(只有文本,而不是p标签本身。)
.html()将为您提供文本和标记。$(body).html()会给你整个HTML页面
.val()适用于具有value属性的元素,例如input。 输入不包含文本或HTML,因此.text()和. 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();
});
不同的是.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/
$('.div'). HTML (val)将设置所有选定元素的HTML值,$('.div').text(val)将设置所有选定元素的文本值。
jQuery.text()的API文档
jQuery.html()的API文档
我猜它们分别对应于node# textContent和Element#innerHTML。(Gecko DOM参考)。
当您打算将值显示为简单文本时,请使用.text(…)。
当您打算将值显示为html格式的文本(或html内容)时,使用.html(…)。
当你不确定你的文本(例如来自输入控件)不包含在HTML中有特殊意义的字符/标记时,你一定要使用.text(…)。这是非常重要的,因为这可能会导致文本不能正常显示,但也可能导致不需要的JS脚本片段(例如来自另一个用户输入)被激活。