1. 程式人生 > >jQuery事件型別

jQuery事件型別

jQuery事件

  1. 事件驅動:目的是將一個事件內容傳遞給另一個事件內容,傳遞的是私有區域性資料,各個事件相互獨立,所以事件可刪除和新增,不會相互影響。注入資料用set、get。
  2. 注入式驅動:AJAX將資料注入到大介面,然後大介面再注入給模組,模組再注入給事件。

事件型別

  1. 繫結
$("<div></div>").appendTo("body").css("backgroundColor","red").width(100).height(100)
	.bind("click",clickHandler);
//該方法無論建立多少div,都只會執行一次函式
$("<div></div>").appendTo("body").css("backgroundColor","red").width(100).height(100)
	.bind("click",function(e){ });
//匿名函式,該方法建立多少div就會執行多少次函式
$("<div></div>").appendTo("body").css("backgroundColor","red").width(100).height(100)
	.bind("mouseenter mouseleave",function(e){ });
//偵聽多個事件,執行一個方法。
$("<div></div>").appendTo("body").css("backgroundColor","red").width(100).height(100).bind({
	“mouseenter”:function(e){ },
	"mouseleave":function(e){ }
});//偵聽多個事件,執行多個方法。
$("<div></div>").appendTo("body").css("backgroundColor","red").width(100).height(100)
	.bind("click",{a:1,b:2},clickHandler);//不能作為匿名函式傳參
function clickHandler(e){console.log e.data;}//輸出結果為{a:1,b:2}
$("<div></div>").appendTo("body").css("backgroundColor","red").width(100).height(100)
	.bind("click",{a:1,b:2},clickHandler);
$(this).unbind("click".clickHandler);//解除事件繫結,<=>this.removeListener(),this指代div
$("<div></div>").appendTo("body").css("backgroundColor","red").width(100).height(100)
	.bind("click",function(e){console.log("a"),
	"click",function(e){console.log("b");});//輸出結果為abababababab...
$("<div></div>").appendTo("body").css("backgroundColor","red").width(100).height(100)
	.bind("click",function(e){console.log("a"),
	"click",function(e){console.log("b");
	$(this).unbind("click");
});//此時所有事件全部被解綁
  1. 簡寫事件
$("<div></div>").appendTo("body").css("backgroundColor","red").width(100).height(100)
	.click(function(e){ });
$(document).ready(function(){
	console.log("a");
})//DOM建立放入完成後就會執行ready,ready只針對document文件來使用,可做預載入

window.onload=function(){
	console.log("b");
}//頁面中所有內容載入完成後才會執行(包括圖片),所以不可做預載入
  1. 模擬事件
/*trigger是模擬事件的傳輸方法,在建立時會自動冒泡,自動執行預設事件*/
$(document).bind("click",function(e,a,b){
	console.log(e,a,b)}).trigger("click",[3,5]);
$(document).on("click");//偵聽事件
$(document).off("click");//取消事件
$(document).one("click");//只執行一次click,執行完成後就會刪除