本文用可互動的按鈕,完整示範 jQuery 對節點的查找、建立、刪除、複製、替換、包裹,以及屬性與樣式的操作。
<script type="text/javascript">
$(function(){
$("#btnFind").click(function(){
var getValue= $("ul li:eq(1)").text();//獲取第二個元素的值
alert(getValue);
var para=$("p");
var p_text=para.attr("title");//獲取屬性
alert(p_text);
alert(para.attr("title","改變你最喜歡吃的水果").attr("title"));//先改再取值
});
//建立節點:append/prepend為父子,after/before為兄弟
$("#btnCreate").click(function(){
var html=$("<li title= '桃子'>桃子</li><li title= '菠蘿'> 菠蘿</li>");
var li2=$("ul li:eq(1)").before(html);//加在第二個li前面
});
$("#btnDelete").click(function(){
var li2=$("ul li:eq(1)").empty();//清空第二個節點
});
$("#btnCopy").click(function(){
$("p").clone().appendTo("ul");
});
$("#btnReplace").click(function(){
$("p").replaceWith("<strong>你最不喜歡的水果是?哈哈</strong>");
});
$("#btnWrap").click(function(){
$("strong").wrapInner("<b></b>");//將strong的內容用b包裹
});
})
</script>
重點:append/prepend 加在元素內部(父子關係),after/before 加在元素前後(兄弟關係);wrap 類方法則是「包裹」,wrap 逐一包裹、wrapAll 一起包裹、wrapInner 包裹內部內容。
<script type="text/javascript">
$(function(){
$("#btnSetOrGetAttr").click(function(){
var p = $("p").attr("title");//獲取屬性
alert(p);
var pSet=$("p").attr("title","這是我重新設置的title屬性哈");
alert(pSet.attr("title"));
});
$("#btnDeleteAttr").click(function(){
var p=$("p").removeAttr("title");
alert(p.attr("title"));
});
$("#btnSetOrGetStyle").click(function(){
var pSet=$("p").attr("class","height");//設置class
alert(pSet.attr("class"));
});
$("ul li").click(function(){
$(this).addClass("another");//追加class,同屬性後者覆蓋前者
});
$("#btnRemoveStyle").click(function(){
$("ul li").removeClass();//移除所有class
var flag = $("p").hasClass("another");//是否含某樣式
alert(flag);
});
})
</script>
屬性用 attr() 讀寫、removeAttr() 移除;樣式則可用 addClass()、removeClass()、hasClass() 操作 class。當一個元素有多個 class 時,樣式會合併,相同屬性以在後者覆蓋前者。