• jQuery Video Tutorials

jQuery text() 方法



jQuery 中的text() 方法用於設定獲取所選元素的文字內容。

當用於設定文字內容時,它會修改或覆蓋匹配元素的內容。

當我們使用此方法獲取文字內容時,它將返回第一個匹配元素的內容。

要操作所選元素的文字和 HTML 標記,請使用html() 方法。

語法

我們有不同的語法來設定和返回文字內容,我們將在下面描述它們:

以下是 jQuery 中 text() 方法用於返回文字內容的語法

$(selector).text()

這是設定文字內容的語法

$(selector).text(content)

以下是使用函式設定文字內容的語法

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

引數

此方法接受以下引數:

  • content: 包含要為所選元素設定的文字內容的字串。
  • function (index,currentcontent): 將為選擇器匹配的每個元素執行的函式。
  • index: 匹配元素集中當前元素的索引位置。
  • currentcontent: 正在處理的元素的當前文字內容。

示例 1

在以下示例中,我們使用 text() 方法設定所有段落元素的文字內容:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function(){
    $("button").click(function(){
      $("p").text("Boom...text has been changed!");
    })
  });
</script>
</head>
<body>
<p>Paragraph element 1.</p>
<p>Paragraph element 2.</p>
<button>Click</button>
</body>
</html>

當我們執行並單擊按鈕時,它將為 DOM 中的所有 <p> 元素設定提供的文字內容。

示例 2

在這個示例中,我們返回所選元素的文字內容。在我們的例子中,所選元素是段落元素:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function(){
    $("button").click(function(){
      alert($("p").text());
    })
  });
</script>
</head>
<body>
<p>Paragraph element 1.</p>
<p>Paragraph element 2.</p>
<button>Click</button>
</body>
</html>

單擊按鈕後,它將返回 DOM 中所有 <p> 元素的文字內容。

示例 3

在這裡,我們使用函式來設定所選元素的文字內容:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function(){
    $("button").click(function(){
      $("p").text(function(index){
        return "Index of this paragraph element is: " + index;
      });
    })
  });
</script>
</head>
<body>
<p>Paragraph element 1.</p>
<p>Paragraph element 2.</p>
<p>Paragraph element 3.</p>
<button>Click</button>
</body>
</html>

當我們執行並單擊按鈕時,它將為 DOM 中的所有 <p> 元素設定提供的文字內容並返回其索引值。

jquery_ref_html.htm
廣告