.text()


取得符合元素組中每個元素的合併文字內容,包含其後代,或設定符合元素的文字內容。

.text()傳回: 字串

說明: 取得符合元素組中每個元素的合併文字內容,包含其後代。

  • 新增版本: 1.0.text()

    • 此方法不接受任何參數。

.html() 方法不同,.text() 可同時用於 XML 和 HTML 文件。.text() 方法的結果為包含所有符合元素合併文字的字串。(由於不同瀏覽器的 HTML 解析器有差異,傳回的文字可能會在換行符號和其他空白處有所不同。)請考慮以下 HTML

1
2
3
4
5
6
7
<div class="demo-container">
<div class="demo-box">Demonstration Box</div>
<ul>
<li>list item 1</li>
<li>list <strong>item</strong> 2</li>
</ul>
</div>

程式碼 $( "div.demo-container" ).text() 會產生下列結果

示範方塊清單項目 1 清單項目 2

.text() 方法無法用於表單輸入或指令碼。若要設定或取得 inputtextarea 元素的文字值,請使用 .val() 方法。若要取得指令碼元素的值,請使用 .html() 方法。

從 jQuery 1.4 開始,.text() 方法會傳回文字和 CDATA 節點以及元素節點的值。

範例

在第一個段落中尋找文字(移除 HTML),然後設定最後一個段落的 HTML 以顯示它只是文字(紅色粗體已消失)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>text demo</title>
<style>
p {
color: blue;
margin: 8px;
}
b {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
</head>
<body>
<p><b>Test</b> Paragraph.</p>
<p></p>
<script>
var str = $( "p" ).first().text();
$( "p" ).last().html( str );
</script>
</body>
</html>

示範

.text( text )傳回:jQuery

說明:將符合的元素集合中每個元素的內容設定為指定的文字。

  • 新增版本:1.0.text( text )

    • text
      類型:字串數字布林
      設定為每個符合元素內容的文字。提供數字或布林時,它會轉換為字串表示形式。
  • 新增版本:1.4.text( function )

    • function
      類型:函式( 整數 index, 字串 text ) => 字串
      傳回要設定的文字內容的函數。接收集合中元素的索引位置和舊的文字值作為參數。

.html() 方法不同,.text() 可同時用於 XML 和 HTML 文件。

我們需要知道,此方法會視需要跳脫提供的字串,以便在 HTML 中正確呈現。為此,它會呼叫 DOM 方法 .createTextNode(),不會將字串解釋為 HTML。考慮以下 HTML

1
2
3
4
5
6
7
<div class="demo-container">
<div class="demo-box">Demonstration Box</div>
<ul>
<li>list item 1</li>
<li>list <strong>item</strong> 2</li>
</ul>
</div>

程式碼 $( "div.demo-container" ).text( "<p>This is a test.</p>" ); 會產生以下 DOM 輸出

1
2
3
<div class="demo-container">
&lt;p&gt;This is a test.&lt;/p&gt;
</div>

它會在已呈現的頁面上顯示,就像標籤已公開,如下所示

1
<p>This is a test</p>

.text() 方法無法用於輸入元素。對於輸入欄位文字,請使用 .val() 方法。

從 jQuery 1.4 開始,.text() 方法允許我們透過傳入函數來設定文字內容。

1
2
3
$( "ul li" ).text(function( index ) {
return "item number " + ( index + 1 );
});

假設有一個無序清單包含三個 <li> 元素,此範例會產生以下 DOM 輸出

1
2
3
4
5
<ul>
<li>item number 1</li>
<li>item number 2</li>
<li>item number 3</li>
</ul>

範例

將文字新增至段落(請注意粗體標籤已跳脫)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>text demo</title>
<style>
p {
color: blue;
margin: 8px;
}
</style>
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
</head>
<body>
<p>Test Paragraph.</p>
<script>
$( "p" ).text( "<b>Some</b> new text." );
</script>
</body>
</html>

示範