jQuery: text() 和 html() 有什么区别? [英] What is the difference between jQuery: text() and html() ?
问题描述
jQuery 中的 text() 和 html() 函数有什么区别?
What the difference between text() and html() functions in jQuery ?
$("#div").html('<a href="example.html">Link</a><b>hello</b>');
对比
$("#div").text('<a href="example.html">Link</a><b>hello</b>');
推荐答案
我认为差异几乎是不言自明的.而且测试起来超级简单.
I think the difference is nearly self-explanatory. And it's super trivial to test.
jQuery.html()
将字符串视为 HTML,jQuery.text()
将内容视为文本
jQuery.html()
treats the string as HTML, jQuery.text()
treats the content as 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 文档中描述了一个可能不太明显的区别
A difference that may not be so obvious is described in the jQuery API documentation
在 .html() 的文档中:
.html()
方法在 XML 文档中不可用.
The
.html()
method is not available in XML documents.
在 .text() 的文档中:
与 .html()
方法不同,.text()
可以在 XML 和 HTML 文档中使用.
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>
http://jsfiddle.net/hossain/sUTVg/
这篇关于jQuery: text() 和 html() 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!