jQuery - 取得內(nèi)容和屬性
jQuery DOM 操作
jQuery 中非常重要的部分,就是操作 DOM 的能力。
jQuery 提供一系列與 DOM 相關(guān)的方法,這使得存取和操作元素和屬性變得容易。
三個(gè)簡(jiǎn)單實(shí)用的用於DOM 操作的jQuery 方法:
text() - 設(shè)定或返回所選元素的文字內(nèi)容
html() - 設(shè)定或傳回所選元素的內(nèi)容(包括HTML 標(biāo)記)
##val() - 設(shè)定或傳回表單欄位的值
示範(fàn)如何透過(guò)jQuery text() 和html() 方法來(lái)取得內(nèi)容:
<!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(){ alert("Text: " + $("#test").text()); }); $("#btn2").click(function(){ alert("HTML: " + $("#test").html()); }); }); </script> </head> <body> <p id="test">這是段落中的 <b>粗體</b> 文本。</p> <button id="btn1">顯示文本</button> <button id="btn2">顯示 HTML</button> </body> </html>
#示範(fàn)如何透過(guò)jQuery val() 方法獲得輸入欄位的值:
<!DOCTYPE html> <html> <meta charset="utf-8"> <head> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ alert("值為: " + $("#test").val()); }); }); </script> </head> <body> <p>名稱(chēng): <input type="text" id="test" value="php中文網(wǎng)"></p> <button>顯示值</button> </body> </html>
##attr()屬性
<!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(){ alert($("#php").attr("href")); }); }); </script> </head> <body> <p><a href="http://www.miracleart.cn" id="php">php中文網(wǎng)</a></p> <button>顯示 href 屬性的值</button> </body> </html>#########