首頁  >  文章  >  web前端  >  jQuery文件操作中text()的用法

jQuery文件操作中text()的用法

一个新手
一个新手原創
2017-10-06 10:43:011512瀏覽

定義和用法
text() 方法方法設定或傳回被選元素的文字內容。它主要包括三點:
1. 設定 2.返回 3.使用函數設定文字內容。

1設定文字內容
當方法用於設定值時,它會覆寫被選取元素的所有內容。
範例:
$(selector).text(content)
參數            content
描述         規定選取元素的新文字內容。註:特殊字元會被編碼。

<html><head><script type="text/javascript" src="/jquery/jquery.js"></script><script type="text/javascript">$(document).ready(function(){
  $(".btn1").click(function(){
    $("p").text("Hello world!");
  });
});</script></head><body><p>This is a paragraph.</p><p>This is another paragraph.</p><button class="btn1">改变所有 p 元素的文本内容</button></body></html>

jQuery文件操作中text()的用法
點擊之後結果:
jQuery文件操作中text()的用法

#2.傳回文字內容
當方法用來傳回一個值時,它會傳回所有符合元素的組合的文字內容(會刪除HTML 標記)。
$(selector).text()
例如:

<html><head><script type="text/javascript" src="/jquery/jquery.js"></script><script type="text/javascript">$(document).ready(function(){
  $(".btn1").click(function(){
    alert($("p").text());
  });
});</script></head><body><p>This is a paragraph.</p><p>This is another paragraph.</p><button class="btn1">获得 p 元素的文本内容</button></body></html>

jQuery文件操作中text()的用法
#點擊之後
jQuery文件操作中text()的用法
這樣就把想要回傳標籤裡面內容的值回傳出來。
3.使用函數設定文字內容
使用函數設定所有被選元素的文字內容。
語法

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

參數      function(index,oldcontent)
說明      必要。規定傳回被選元素的新文字內容的函數。
index - 可選。接受選擇器的 index 位置。
html - 可選。接受選擇器的目前內容。

例如

<html><head><script type="text/javascript" src="/jquery/jquery.js"></script><script type="text/javascript">$(document).ready(function(){
  $("button").click(function(){
    $("p").text(function(n){
    return "这个 p 元素的 index 是:" + n;
    });
  });
});</script></head><body><p>This is a paragraph.</p><p>This is another paragraph.</p><button class="btn1">改变所有 p 元素的文本内容</button></body></html>

jQuery文件操作中text()的用法
點擊之後返回結果
jQuery文件操作中text()的用法

以上是jQuery文件操作中text()的用法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn