jquery 操作DOM的基本用法分享
2024-05-06 14:22:08
供稿:網友
例子展示:
jquery代碼:
代碼如下:
<script language="javascript">
$(document).ready(function(){
alert($("ul li:eq(1)").text()); //選取第二個li的值
alert($("p").attr("title")); //選取p的title屬性的值
//追加元素
$('ul').append("<li title='香蕉'>香蕉</li>").append("<li title='雪梨'>雪梨</li>");
//前面追加
$('ul').prepend("<li title='欠佳'>前加</li>");
//后面追加
$('ul').after("<li title='后加'>后加</li>");
//在p后面添加
$("<b> 你好</b>").insertAfter("p");
//在p前面添加
$("<b> 你好</b>").insertBefore("p");
//刪除節點
$("ul :eq(1)").remove();
// 清空值
$("ul :eq(2)").empty();
//復制節點
$("ul li").click(function(){
$(this).clone(true).appendTo("ul");//true可有可無,有表示在復制的時候同時把綁定的事件也復制上
});
//替換節點
$("p[title=test]").replaceWith("<strong>你最喜歡的水果是?</strong>");
//$("<strong>你最喜歡的水果是?</strong>").replaceAll("P");
//包裹事件
$("strong").wrap("<b></b>")
//屬性操作
$("P").attr({"title":"test","name":"pName"}); //添加屬性
$("p").removeAttr("title"); //移除屬性
//樣式的操作
/*
添加樣式: $("p").addClass("hight");
已出樣式: $("p").removeClass("highr");
切換樣式: $("p").toggleClass("another");
是否有樣式: $("p").hasCLass("higth");
*/
alert($("p").html()); //獲取值 html()類似于javascript中的innerHTML屬性
$("p").html("change"); //改變值
alert($("p").text()); //獲取值 text()類似于javascript中的innerTEXT屬性
$("p").text("again change"); //改變值
$("#name").focus(function(){
if($("#name").val()=="請輸入用戶名"){
$(this).val("");
}
}).blur(function(){
if($("#name").val()==""){
$(this).val("請輸入用戶名");
}
});
$("#password").focus(function(){
$("#tip").hide();
}).blur(function(){
if($("#password").val()==""){
$("#tip").show(200);
}
});
$("#submit").click(function(){
if($("#name").val()=="請輸入用戶名"||$("#password").val()==""){
$("#name").css("background","yellow");
$("#password").css("background","yellow");
}
});
$("#single").val("選擇2");
$("#multiple").val(["選擇2號","選擇3號"]);
$(":checkbox").val(["check2","check3"]);
$(":radio").val(["radio1"]);
alert("careful!");
$("#single :eq(2)").attr("selected",true);
$("[value=radio2]:radio").attr("checked",true);
//遍歷節點 children()方法
$("#btnShow").click(function(){
for(var i=0;i<$("body").children().length;i++){
$("#body").append($("body").children()[i].innerHTML);
}
});
//next()方法,取得緊挨p后面的同輩的所有元素
alert($("ul li").next().text());
//prev()方法,取得緊挨匹配前面的同輩的一個元素