jQuery: text() 和 html() 之间有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1910794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:23:36  来源:igfitidea点击:

What is the difference between jQuery: text() and html() ?

jquerydom

提问by Brettk

What the difference between text() and html() functions in jQuery ?

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>');

回答by Peter Bailey

I think the difference is nearly self-explanatory. And it's super trivial to test.

我认为差异几乎是不言自明的。而且测试起来非常简单。

jQuery.html()treats the string as HTML, jQuery.text()treats the content as text

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>

A difference that may not be so obvious is described in the jQuery API documentation

jQuery API 文档中描述了一个可能不太明显的区别

In the documentation for .html():

.html()的文档中:

The .html()method is not available in XML documents.

.html()方法在 XML 文档中不可用。

And in the documentation for .text():

.text()的文档中:

Unlike the .html()method, .text()can be used in both XML and HTML documents.

与该.html()方法不同,.text()可以在 XML 和 HTML 文档中使用。

$(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/http://jsfiddle.net/hossain/sUTVg/

回答by Peter Krauss

((please update if necessary, this answer is a Wiki))

((如有必要,请更新,这个答案是一个维基))

Sub-question: when only text, what is faster, .text()or .html()?

子问题:当只有文本时,什么更快,.text()或者.html()

Answer:.html()is faster! See here a "behaviour test-kit" for all the question.

答:.html()更快!见这里的“行为测试试剂盒”的所有问题

So, in conclusion, if you have "only a text", use html()method.

因此,总而言之,如果您“只有文本”,请使用html()方法。

Note:Doesn't make sense? Remember that the .html()function is only a wrapper to .innerHTML, but in the .text()function jQuery adds an "entity filter", and this filter naturally consumes time.

注意:没有意义?请记住,该.html()函数只是对 的包装器.innerHTML,但在.text()函数中 jQuery 增加了一个“实体过滤器”,这个过滤器自然会消耗时间。



Ok, if you really want performance... Use pure Javascriptto access direct text-replace by the nodeValueproperty. Benchmark conclusions:

好的,如果你真的想要性能......使用纯 Javascript访问nodeValue属性的直接文本替换。基准结论:

  • jQuery's .html()is ~2x faster than .text().
  • pure JS' .innerHTMLis ~3x faster than .html().
  • pure JS' .nodeValueis ~50x faster than .html(), ~100x than .text(), and ~20x than .innerHTML.
  • jQuery.html().text().
  • 纯 JS'.innerHTML.html().
  • 纯 JS'.nodeValue比 快约 50.html()倍,比快约 100 倍.text(),比.innerHTML.

PS: .textContentproperty was introduced with DOM-Level-3, .nodeValueis DOM-Level-2 and is faster (!).

PS:.textContent属性是在 DOM-Level-3 中引入的,.nodeValue是 DOM-Level-2 并且更快(!)。

See this complete benchmark:

请参阅此完整的基准测试

// 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());

回答by Andrew Hare

The first example will actually embed HTML within the divwhereas the second example will escape the text by means of replacing element-related characters with their corresponding character entitiesso that it displays literally (i.e. the HTML will be displayednot rendered).

第一个示例实际上将 HTML 嵌入到其中,div而第二个示例将通过将与元素相关的字符替换为其相应的字符实体来转义文本,以便它按字面显示(即 HTML 将被显示而不是呈现)。

回答by davidcl

The text()method entity-escapes any HTML that is passed into it. Use text()when you want to insert HTML code that will be visible to people who view the page.

text()方法实体转义任何传入它的 HTML。text()当您想要插入对查看页面的人可见的 HTML 代码时使用。

Technically, your second example produces:

从技术上讲,你的第二个例子产生:

&lt;a href="example.html"&gt;Link&lt;/a&gt;&lt;b&gt;hello&lt;/b&gt;

which would be rendered in the browser as:

这将在浏览器中呈现为:

<a href="example.html">Link</a><b>hello</b>

Your first example will be rendered as an actual link and some bold text.

您的第一个示例将呈现为实际链接和一些粗体文本。

回答by Owais Qureshi

Actually both do look somewhat similar but are quite different it depends on your usage or intention what you want to achieve ,

实际上,两者看起来确实有些相似,但完全不同,这取决于您的用途或意图要实现的目标,

Where to use:

使用地点:

  • use .html()to operate on containers having html elements.
  • use .text()to modify text of elements usually having separate open and closing tags
  • 用于.html()操作具有 html 元素的容器。
  • 用于.text()修改通常具有单独的开始和结束标记的元素的文本

Where not to use:

不该使用的地方:

  • .text()method cannot be used on form inputs or scripts.

    • .val()for input or textarea elements.
    • .html()for value of a script element.
  • Picking up html content from .text()will convert the html tags into html entities.

  • .text()方法不能用于表单输入或脚本。

    • .val()用于输入或 textarea 元素。
    • .html()用于脚本元素的值。
  • 从中获取 html 内容.text()会将 html 标签转换为 html 实体。

Difference:

区别:

  • .text()can be used in both XML and HTML documents.
  • .html()is only for html documents.
  • .text()可以在 XML 和 HTML 文档中使用。
  • .html()仅适用于 html 文档。

Check this example on jsfiddle to see the differences in action

在 jsfiddle 上查看此示例以查看操作上的差异

Example

例子

回答by Deb

Strange that no-one mentioned the Cross Site scripting prevention benefit of .text()over .html()(Although others have just mentioned that .text()escapes the data).

奇怪的是,没有人提到.text()over的跨站点脚本预防好处.html()(尽管其他人刚刚提到了.text()转义数据)。

It's always recommended to use .text()when you want to update data in DOM which is just data / text for the user to see.

.text()当您想更新 DOM 中的数据时,始终建议使用它,而这些数据只是供用户查看的数据/文本。

.html()should be mostly used to get the HTML content within a div.

.html()应该主要用于获取 div 中的 HTML 内容。

回答by Adorjan Princz

Use .text(…) when you intend to display the value as a simple text.

当您打算将值显示为简单文本时,请使用 .text(...)。

Use .html(…) when you intend to display the value as a html formatted text (or HTML content).

当您打算将值显示为 html 格式的文本(或 HTML 内容)时,请使用 .html(...)。

You should definitely use .text(...)when you're not sure that your text (e.g. coming from an input control) do not contain characters/tags that has special meaning in HTML. This is really importantbecause this could result in the text will not display properly but it could also cause that an unwanted JS script snippet (e.g. coming from another user input) to be activated.

当您不确定您的文本(例如来自输入控件)不包含在 HTML 中具有特殊含义的字符/标签时,您绝对应该使用 .text(...)这非常重要,因为这可能导致文本无法正确显示,但也可能导致不需要的 JS 脚本片段(例如来自另一个用户输入)被激活

回答by Mustkeem K

Well in simple term.

简单来说。

html()-- to get inner html(html tags and text).

html()-- 获取内部 html(html 标签和文本)。

text()-- to get only text if present inside(only text)

text()-- 如果存在于内部,则仅获取文本(仅文本)

回答by Seth

Basically, $("#div").html uses element.innerHTML to set contents, and $("#div").text (probably) uses element.textContent.

基本上,$("#div").html 使用 element.innerHTML 来设置内容,而 $("#div").text(可能)使用 element.textContent。

http://docs.jquery.com/Attributes/html:

http://docs.jquery.com/Attributes/html

Set the html contents of every matched element

http://docs.jquery.com/Attributes/text:

http://docs.jquery.com/Attributes/text

Similar to html(), but escapes HTML (replace "<" and ">" with their HTML 
entities).

回答by Michiel Kalkman

$('.div').html(val)will set the HTML values of all selected elements, $('.div').text(val)will set the text values of all selected elements.

$('.div').html(val)将设置所有选定元素的 HTML 值,$('.div').text(val)将设置所有选定元素的文本值。

API docs for jQuery.text()

jQuery.text() 的 API 文档

API docs for jQuery.html()

jQuery.html() 的 API 文档

I would guess that they correspond to Node#textContentand Element#innerHTML, respectively. (Gecko DOM references).

我猜它们分别对应于Node#textContentElement#innerHTML。(Gecko DOM 参考)。