JQuery中的Dom操作和事件
(一)JQuery中的事件
1.常規事件,把js事件中的on去掉
復合事件:hover(function(){},function(){}) ---- 相當於把鼠標移入移出事件和在一起執行
toggle(function(){},function(){},....)可以寫多個,點擊事件循環執行
未來元素:對象.live("事件名",function(){}); --- 對未來創建的元素進行操作
列子:點擊按鈕,創建元素,並給創建的元素添加點擊事件
//對象.append();在什麽對象下添加元素 $("html中要創建的內容")
$("#boss").append($("<div class=‘div1‘></div>"));
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <script src="Js/jquery-1.7.1.min.js"></script> <title></title> <style type="text/css"> .div1 { width:100px; height:100px; margin-left:20px; margin-top:20px; float:left; background-color:red; } </style> </head> <body> <form id="form1" runat="server"> <input type="button" value="提交" id="but"/> <div style="width:800px;height:600px;" id="boss"> <div class="div1"> </div> <div class="div1"> </div> <div class="div1"> </div> </div> </form> </body> </html> <script type="text/javascript"> //對象.live未來事件 $(".div1").live("click",function () { alert("aaa"); }); $("#but").click(function () { //對象.append();在什麽對象下添加元素 $("html中要創建的內容") $("#boss").append($("<div class=‘div1‘></div>")); }); </script>
2.阻止事件冒泡的方法:直接在事件中加入 return false;
(二)Dom操作
1.操作屬性:
獲取屬性:var s = $("選擇器").attr("屬性名")
設置屬性:$("選擇器").attr("屬性名","屬性值")
刪除屬性:$("選擇器").removeAttr("屬性名")
2.操作樣式:
操作樣式:獲取樣式: var s = $("選擇器").css("樣式名")
設置樣式:$("選擇器").css("樣式名","值")
操作樣式表的class:添加class $("選擇器").addClass("class名")
移出class $("選擇器").removeClass("class名")
添加移除交替class $("選擇器").toggleClass("class名")
3.操作內容:
表單元素的取值賦值和js中的一樣,非表單元素中,.html賦值:標記會編譯,取值:標記會取出
.text賦值:內容直接全部輸入,取值:只取出文字內容
表單元素:
取值:var s = $("選擇器").val()
賦值: $("選擇器").val("值")
非表單元素:
取值:var s = $("選擇器").html(), var s = $("選擇器").text()
賦值:$("選擇器").html("內容"), $("選擇器").text("內容")
4.操作相關元素:
查找:父輩 --- parent() 前輩 --- parents(選擇器)
子級 --- children(選擇器) 後代 --- find(選擇器)
兄弟(哥哥) --- prev() ,prevAll(選擇器) 弟弟 --- next()後面一個元素 nextAll(選擇器)後面兄弟級的元素
操作:新建元素$("html字符串")
添加:對象.appen(jquery對象) --- 內部添加,給什麽對象添加
after(jquery對象) --- 下部平級添加
before(jquery對象) --- 上部平級添加
移出:empty() --- 清空內部全部元素
remove() --- 移出元素
復制:clone()
JQuery中的Dom操作和事件