jquery - jQuery : text() and html() ? 有什么区别

标签 jquery dom

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>
http://jsfiddle.net/hossain/sUTVg/ 上进行现场演示

关于jquery - jQuery : text() and html() ? 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1910794/

相关文章:

php - HTML 标签之间内容的 XPath 查询

php - 如何解析$.get()函数获取的数据

javascript - 在其他页面打开 jQuery Fancybox

jquery - 如何在多次 Backbone 保存后发出一个 AJAX 请求

jQuery 选择器 : Grabbing a section of children that are of a given tag

java - Java 中带有参数的高效 XSLT 管道

css - 执行与 Firebug、Chrome 开发者工具等类似功能的网站

javascript - "class"属性的值隐式扩展某些标记元素

javascript - 如何突出显示中继器中选定的行?

javascript - 如何应用 EXIF 方向