jQuery - 設(shè)定內(nèi)容和屬性
設(shè)定內(nèi)容- text()、html() 以及val()
使用前一章中的三個(gè)相同的方法來(lái)設(shè)定內(nèi)容:
text() - 設(shè)定或傳回所選元素的文字內(nèi)容
html() - 設(shè)定或傳回所選元素的內(nèi)容(包括HTML 標(biāo)記)
val() - 設(shè)定或傳回表單欄位的值
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("#btn1").click(function(){ $("#test1").text("歡迎!"); }); $("#btn2").click(function(){ $("#test2").html("<b>Hello world!</b>"); }); $("#btn3").click(function(){ $("#test3").val("php"); }); }); </script> </head> <body> <p id="test1">段落1</p> <p id="test2">段落2</p> <p>輸入框: <input type="text" id="test3" value="php中文網(wǎng)"></p> <button id="btn1">設(shè)置文本</button> <button id="btn2">設(shè)置 HTML</button> <button id="btn3">設(shè)置值</button> </body> </html>
text()、html() 以及val() 的回呼函數(shù)
上面的三個(gè)jQuery 方法:text()、html() 以及val(),同樣擁有回呼函數(shù)。
回呼函數(shù)由兩個(gè)參數(shù):
被選元素清單中目前元素的下標(biāo),以及原始(舊的)值。
然後以函數(shù)新值傳回您希望使用的字串。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("#btn1").click(function(){ $("#test1").text(function(i,origText){ return "舊文本: " + origText + " 新文本: Hello world! (index: " + i + ")"; }); }); $("#btn2").click(function(){ $("#test2").html(function(i,origText){ return "舊 html: " + origText + " 新 html: Hello <b>world!</b> (index: " + i + ")"; }); }); }); </script> </head> <body> <p id="test1">這是一個(gè)有 <b>粗體</b> 字的段落。</p> <p id="test2">這是另外一個(gè)有 <b>粗體</b> 字的段落。</p> <button id="btn1">顯示 新/舊 文本</button> <button id="btn2">顯示 新/舊 HTML</button> </body> </html>
attr()設(shè)定屬性
attr() 方法允許您同時(shí)設(shè)定多個(gè)屬性。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("#php").attr({ "href" : "http://miracleart.cn/jquery", "title" : "jQuery 教程" }); }); }); </script> </head> <body> <p><a href="http://miracleart.cn" id="php">php中文網(wǎng)</a></p> <button>修改 href 和 title</button> <p>點(diǎn)擊按鈕修改后,可以查看 href 和 title 是否變化。</p> </body> </html>
attr() 的回呼函數(shù)
#回呼函數(shù)由兩個(gè)參數(shù):
被選元素清單中目前元素的下標(biāo),以及原始(舊的)值。
然後以函數(shù)新值傳回您希望使用的字串。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("#php").attr("href", function(i, origValue){ return origValue + "/jquery"; }); }); }); </script> </head> <body> <p><a href="http://miracleart.cn" id="php">php中文網(wǎng)</a></p> <button>修改 href 值</button> <p>點(diǎn)擊按鈕修改后,可以點(diǎn)擊鏈接查看 href 屬性是否變化。</p> </body> </html>