jQuery 中的 text() 和 html() 函数有什么区别?
$("#div").html('<a href="example.html">Link</a><b>hello</b>');
对比
$("#div").text('<a href="example.html">Link</a><b>hello</b>');
最佳答案
我认为差异几乎是不言自明的。而且测试起来非常简单。
jQuery.html()
将字符串视为 HTML,jQuery.text()
将内容视为文本
<html>
<head>
<title>Test Page</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#div1").html('<a href="example.html">Link</a><b>hello</b>');
$("#div2").text('<a href="example.html">Link</a><b>hello</b>');
});
</script>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
</body>
</html>
jQuery API 文档中描述了一个可能不那么明显的区别
在 .html() 的文档中:
The
.html()
method is not available in XML documents.
并且在 .text() 的文档中:
Unlike the
.html()
method,.text()
can be used in both XML and HTML documents.
$(function() {
$("#div1").html('<a href="example.html">Link</a><b>hello</b>');
$("#div2").text('<a href="example.html">Link</a><b>hello</b>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<div id="div1"></div>
<div id="div2"></div>
关于jquery - jQuery : text() and html() ? 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1910794/