jQuery DOM 操作
jQuery 中非常重要的部分,就是操作 DOM 的能力。
jQuery 提供一系列與 DOM 相關的方法,這使訪問和操作元素和屬性變得很容易。
提示:DOM = Document Object Model(文檔對象模型)
DOM 定義訪問 HTML 和 XML 文檔的標準:
1.獲得或設置元素內容
三個簡單實用的用於 DOM 操作的 jQuery 方法:
- text() - 設置或返回所選元素的文本內容
- html() - 設置或返回所選元素的內容(包括 HTML 標記)
- val() - 設置或返回表單字段的值
<script> $(document).ready(function(){ $("#btn1").click(function(){ alert("Text: " + $("#test").text()); }); $("#btn2").click(function(){ alert("HTML: " + $("#test").html()); }); }); </script>
<script> $(document).ready(function(){ $("#btn1").click(function(){ var textStr = $("#test").text(); //獲取段落中文本內容 $("#test").text(textStr ); }); $("#btn2").click(function(){ var htmlStr=$("p").html(); //獲取段落中HTML內容 $("test").text (htmlStr ); }); }); </script>
2.獲取或設置元素的屬性 - attr()
jQuery attr() 方法用於獲取屬性值。
$("img").attr("src"); //獲取圖像地址
<script>
$(document).ready(function(){
$("button").click(function(){
alert($("#w3s").attr("href"));
});
});
</script>
3.添加新的 HTML 內容
我們將學習用於添加新內容的四個 jQuery 方法:
- append() - 在被選元素的結尾插入內容
- prepend() - 在被選元素的開頭插入內容
- after() - 在被選元素之後插入內容
- before() - 在被選元素之前插入內容
jQuery append() 方法
jQuery append() 方法在被選元素的結尾插入內容。
$("p").append("Some appended text.");
jQuery prepend() 方法
jQuery prepend() 方法在被選元素的開頭插入內容。
$("p").prepend("Some prepended text.");
jQuery after() 和 before() 方法
jQuery after() 方法在被選元素之後插入內容。
jQuery before() 方法在被選元素之前插入內容。
$("img").after("Some text after");
$("img").before("Some text before");
刪除元素/內容
如需刪除元素和內容,一般可使用以下兩個 jQuery 方法:
- remove() - 刪除被選元素(及其子元素)
- empty() - 從被選元素中刪除子元素
jQuery 操作 CSS
jQuery 擁有若干進行 CSS 操作的方法。我們將學習下面這些:
- addClass() - 向被選元素添加一個或多個類
- removeClass() - 從被選元素刪除一個或多個類
- toggleClass() - 對被選元素進行添加/刪除類的切換操作
- css() - 設置或返回樣式屬性
<style type="text/css"> .important { font-weight:bold; font-size:xx-large; } .blue { color:blue; } </style> <script> $(document).ready(function(){ $("button").click(function(){ $("h1,h2,p").addClass("blue"); $("div").addClass("important"); }); }); </script>
jQuery removeClass() 方法
下面的例子演示如何不同的元素中刪除指定的 class 屬性: