📜  jQuery text()

📅  最后修改于: 2020-11-26 00:53:11             🧑  作者: Mango

jQuery text()

jQuery text()方法用于设置或返回所选元素的文本内容。

返回内容:使用此方法返回内容时,它将返回所有匹配元素的组合文本内容,而没有HTML标记。

设置内容:使用此方法设置内容时,它将覆盖所有匹配元素的内容。

jQuery text()方法和jQuery html()方法之间的区别

有时,由于这两种方法都用于设置或返回html内容,所以会造成这种混乱。但是,jQuery text()方法不同于html()方法。

以下是主要区别:

  • jQuery text()方法用于设置或返回没有HTML标记的html内容,而html()方法用于设置或返回innerHtml(文本+ HTML标记)。
  • jQuery text()方法可以在XML和HTML文档中使用,而jQuery html()方法则不能。

句法:

要返回文本内容:

$(selector).text() 

设置文本内容:

$(selector).text(content) 

要使用函数设置文本内容:

$(selector).text(function(index,currentcontent))

jQuery text()方法的参数

Parameter Description
Content It is a mandatory parameter. It specifies the new text content for the selected elements. The special characters will be encoded in this parameter.
Function (index,currentcontent) It is an optional parameter. It specifies the function that returns the new text content for the selected elements.
  • Index: It provides the index position of the element in the set.
  • Currentcontent: It provides the current content of the selected elements.

jQuery text()方法的示例

让我们以一个示例来演示jQuery text()方法的效果。

一个简单的返回内容的示例:




  
  text demo
  
  


Hello! javatpoint.com

输出:

Hello! javatpoint.com

Hello! javatpoint.com

jQuery text()方法的另一个示例

设置内容的示例:









Hello Guys!

Looking for online training....

输出:

Hello Guys!

Looking for online training….