jQuery事件
jquery裏面的事件大概分爲三部分:鍵盤事件 鼠標事件 窗口事件
jquery的結構層和行爲層是分離的,且jquery裏可以進行鏈式操作。
最簡單的寫法
$("#btn").click(function (){ //點擊事件
console.log(2);
}).mouseenter(function (){ //鼠標進入事件
console.log(1);
}).mouseleave(function (){ //鼠標離開事件
console.log(3);
});
獲取事件的對象
$("#btn").click(function(e){
var ele=e.target;
console.log(ele)//可以通過e來獲取當前操作元素的節點
})
事件的綁定
1、通過bind()來綁定 bing(type,data,fn)
$("#btn").bind("click",function (){
alert(1)
})
2、bind()綁定外部函數
$("#btn").bind("click",show)//這裏不用加括號
function show(){
console.log(233)
}
$("#btn").bind("click",2,function(e){
console.log(e)//e是jquery中封裝了e的data屬性,data額外傳輸的數據
console.log(event)//event是js中的,沒有data屬性
}
3、綁定多個事件
$("#btn").bind("click mouseleave",function(e){
if(e.type=="click"){//判斷該給哪個事件加哪些屬性
console.log(1)
}
else{
console.log(2)
}
}).unbind("click mouseleave") // 移除事件
4、特殊的綁定 on()
("#btn").on("click mouseleave",function(e){
if(e.type=="click"){//判斷該給哪個事件加哪些屬性
console.log(1)
}
else{
console.log(2)
}
} //用法基本上和bind一樣
5、bind()和on()的區別
兩者參數
.bind(events [,eventData], handler)
.on(events [,selector] [,data], handler)
.on的selector參數是篩選出調用.on方法的dom元素的指定子元素,就相當於on可以進行子代事件的委託,即子類可以添加上事件,也可以爲動態創建的元素綁上指定事件
$("ul").on("click","li",function(){
$(this).css("backgroundColor","red");
var ele=$("<li>new li</li>");
$(this).parent().append(ele)
})//li上有ul綁定的事件,可以點出來
$("ul").bind("click","li",function(){
$(this).css("backgroundColor","red");
var ele=$("<li>new li</li>");
$(this).parent().append(ele)
})// bind()沒有事件委託,所以不可以委託
6、事件的切換 hover()
$(".b1").mouseover(function (){
console.log(1);
}).mouseleave(function (){
console.log(2);
});
$(".b1").hover(function (){
console.log(1);
},function (){
console.log(2);
});//方法觸發mouseenter 和 mouseleave,切換這兩個方法
7、一次性觸發事件 one()
$(".b1").one("mouseleave",function(){
console.log(1)
}) //只會使用一次
8、指定事件
trigger() 方法觸發被選元素上指定的事件以及事件的默認行爲(比如表單提交)。
trigger()指定事件方法,就是綁定
$("#txt").trigger("select").select(function(){
$(this).css("color","red");
})//自執行,直接是被選擇且爲紅色
$("#txt").focus(function(){
$(this).css("color","red")
})//這個需人爲獲焦
trigger()觸發事件 寫在事件之後
$("#txt").trigger("focus");//加上這個之後打開頁面會自動獲焦
/*自定義事件*/
$("#txt").bind("mytxt",function(e,a,b,c){
console.log(e)
})
$("#txt").trigger("mytxt",[1,2,3])
trigger觸發事件,寫在事件之後,相當於把方法指定,而且自動執行
傳值,值爲數組形式,傳參時,參順着往下寫