
- jQuery 教程
- jQuery - 首頁
- jQuery - 路線圖
- jQuery - 概述
- jQuery - 基礎
- jQuery - 語法
- jQuery - 選擇器
- jQuery - 事件
- jQuery - 屬性
- jQuery - AJAX
- jQuery DOM 操作
- jQuery - DOM
- jQuery - 新增元素
- jQuery - 刪除元素
- jQuery - 替換元素
- jQuery CSS 操作
- jQuery - CSS 類
- jQuery - 尺寸
- jQuery - CSS 屬性
- jQuery 效果
- jQuery - 效果
- jQuery - 動畫
- jQuery - 鏈式操作
- jQuery - 回撥函式
- jQuery 遍歷
- jQuery - 遍歷
- jQuery - 遍歷祖先元素
- jQuery - 遍歷子孫元素
- jQuery UI
- jQuery - 互動
- jQuery - 小部件
- jQuery - 主題
- jQuery 參考
- jQuery - 選擇器
- jQuery - 事件
- jQuery - 效果
- jQuery - HTML/CSS
- jQuery - 遍歷
- jQuery - 其他
- jQuery - 屬性
- jQuery - 工具函式
- jQuery 外掛
- jQuery - 外掛
- jQuery - PagePiling.js
- jQuery - Flickerplate.js
- jQuery - Multiscroll.js
- jQuery - Slidebar.js
- jQuery - Rowgrid.js
- jQuery - Alertify.js
- jQuery - Progressbar.js
- jQuery - Slideshow.js
- jQuery - Drawsvg.js
- jQuery - Tagsort.js
- jQuery - LogosDistort.js
- jQuery - Filer.js
- jQuery - Whatsnearby.js
- jQuery - Checkout.js
- jQuery - Blockrain.js
- jQuery - Producttour.js
- jQuery - Megadropdown.js
- jQuery - Weather.js
- jQuery 有用資源
- jQuery - 常見問題解答
- jQuery - 快速指南
- jQuery - 有用資源
- jQuery - 討論
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
廣告