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

时间:2022-08-23 11:34:39

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

vs

$("#div").text('<a href="example.html">Link</a><b>hello</b>');

12 个解决方案

#1


328  

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

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>

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

#2


97  

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

(如有必要请更新,此答案为Wiki)

Sub-question: when only text, what is faster, .text() or .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 Javascript to access direct text-replace by the nodeValue property. Benchmark conclusions:

好的,如果你真的想要表演……使用纯Javascript来访问nodeValue属性的直接文本替换。基准测试结论:

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

PS: .textContent property was introduced with DOM-Level-3, .nodeValue is DOM-Level-2 and is faster (!).

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

#3


63  

The first example will actually embed HTML within the div whereas the second example will escape the text by means of replacing element-related characters with their corresponding character entities so that it displays literally (i.e. the HTML will be displayed not rendered).

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

#4


53  

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。当您想要插入HTML代码时,请使用text(),该代码对于查看页面的人来说是可见的。

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.

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

#5


24  

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.
  • 使用.html()对具有html元素的容器进行操作。
  • use .text() to modify text of elements usually having separate open and closing tags
  • 使用.text()修改元素的文本,通常有单独的打开和关闭标记

Where not to use:

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

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

    • .val() for input or textarea elements.
    • .val()用于输入或textarea元素。
    • .html() for value of a script element.
    • .html()表示脚本元素的值。
  • Picking up html content from .text() will convert the html tags into html entities.

    从.text()中提取html内容将把html标签转换成html实体。

Difference:

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

Check this example on jsfiddle to see the differences in action

检查jsfiddle上的这个示例,以查看操作上的差异

Example

#6


9  

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()对.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.

当您想要更新DOM中的数据时,建议使用.text(),因为DOM只是供用户查看的数据/文本。

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

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

#7


5  

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 important because 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脚本片段(例如来自另一个用户输入)被激活。

#8


2  

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

基本上,$(" # div”)。html使用元素。innerHTML用于设置内容,以及$(“#div”)。使用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).

#9


1  

$('.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#textContent and Element#innerHTML, respectively. (Gecko DOM references).

我猜它们分别对应于节点#textContent和元素#innerHTML。(壁虎DOM引用)。

#10


1  

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()——只有文本出现时才获取文本(只有文本)

#11


0  

I think that the difference is to insert html tag in text() you html tag do not functions

我认为区别在于在text()中插入html标签,你的html标签没有功能

$('#output').html('You are registered'+'<br>'  +'  '
                     + 'Mister'+'  ' + name+'   ' + sourname ); }

output :

输出:

You are registered <br> Mister name sourname

replacing text() with html()

替换文本和html()()

output

输出

You are registered
Mister name sourname 

then the tag <br> works in html()

然后标签
在html()中工作

#12


-1  

text function set or retrieve the value as plain text, otherwise, HTML function set or retrieve the value as HTML tags to change or modify that. If you want to just change the content then use text(). But if you need to change the markup then you have to use hmtl().

文本函数将值设置或检索为纯文本,否则,将HTML函数设置或检索为HTML标记的值以更改或修改该值。如果您只想更改内容,那么使用text()。但是如果需要更改标记,则必须使用hmtl()。

It's a dummy answer for me after six years, Don't mind.

六年之后,这对我来说是个假答案,别介意。

#1


328  

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

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>

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

#2


97  

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

(如有必要请更新,此答案为Wiki)

Sub-question: when only text, what is faster, .text() or .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 Javascript to access direct text-replace by the nodeValue property. Benchmark conclusions:

好的,如果你真的想要表演……使用纯Javascript来访问nodeValue属性的直接文本替换。基准测试结论:

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

PS: .textContent property was introduced with DOM-Level-3, .nodeValue is DOM-Level-2 and is faster (!).

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

#3


63  

The first example will actually embed HTML within the div whereas the second example will escape the text by means of replacing element-related characters with their corresponding character entities so that it displays literally (i.e. the HTML will be displayed not rendered).

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

#4


53  

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。当您想要插入HTML代码时,请使用text(),该代码对于查看页面的人来说是可见的。

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.

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

#5


24  

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.
  • 使用.html()对具有html元素的容器进行操作。
  • use .text() to modify text of elements usually having separate open and closing tags
  • 使用.text()修改元素的文本,通常有单独的打开和关闭标记

Where not to use:

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

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

    • .val() for input or textarea elements.
    • .val()用于输入或textarea元素。
    • .html() for value of a script element.
    • .html()表示脚本元素的值。
  • Picking up html content from .text() will convert the html tags into html entities.

    从.text()中提取html内容将把html标签转换成html实体。

Difference:

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

Check this example on jsfiddle to see the differences in action

检查jsfiddle上的这个示例,以查看操作上的差异

Example

#6


9  

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()对.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.

当您想要更新DOM中的数据时,建议使用.text(),因为DOM只是供用户查看的数据/文本。

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

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

#7


5  

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 important because 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脚本片段(例如来自另一个用户输入)被激活。

#8


2  

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

基本上,$(" # div”)。html使用元素。innerHTML用于设置内容,以及$(“#div”)。使用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).

#9


1  

$('.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#textContent and Element#innerHTML, respectively. (Gecko DOM references).

我猜它们分别对应于节点#textContent和元素#innerHTML。(壁虎DOM引用)。

#10


1  

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()——只有文本出现时才获取文本(只有文本)

#11


0  

I think that the difference is to insert html tag in text() you html tag do not functions

我认为区别在于在text()中插入html标签,你的html标签没有功能

$('#output').html('You are registered'+'<br>'  +'  '
                     + 'Mister'+'  ' + name+'   ' + sourname ); }

output :

输出:

You are registered <br> Mister name sourname

replacing text() with html()

替换文本和html()()

output

输出

You are registered
Mister name sourname 

then the tag <br> works in html()

然后标签
在html()中工作

#12


-1  

text function set or retrieve the value as plain text, otherwise, HTML function set or retrieve the value as HTML tags to change or modify that. If you want to just change the content then use text(). But if you need to change the markup then you have to use hmtl().

文本函数将值设置或检索为纯文本,否则,将HTML函数设置或检索为HTML标记的值以更改或修改该值。如果您只想更改内容,那么使用text()。但是如果需要更改标记,则必须使用hmtl()。

It's a dummy answer for me after six years, Don't mind.

六年之后,这对我来说是个假答案,别介意。