【jquery 事件绑定】
注意前后俩者对象是父子关系(只要是父子均可)
等价于:
1、添加元素事件绑定
(1) 添加事件为当前元素
$('p').on('click',function(){
//code here ...
});
(2) 添加事件为未来元素(动态添加元素)
$(document父).on('click','p子',function(){
//code here...
})
注意前后俩者对象是父子关系(只要是父子均可)
(3) 多个事件同时绑定
$(document).ready(function(){
$("p").on({
mouseover:function(){$(this).css("background-color","lightgray");},
mouseout:function(){$(this).css("background-color","lightblue");},
click:function(){$(this).css("background-color","yellow");}
});
});
2、移除元素事件绑定
(1) 移除所有的事件
$( "p" ).off();
(2) 移除所有点击事件
$( "p" ).off( "click", "**" );
(3) 移除某个特定的绑定程序
$( "body" ).off( "click", "p", foo );
(4) 解绑某个类相关的所有事件处理程序
$(document).off(".someclass");
3. 添加元素一次事件绑定
一次触发,事件自动解除$( "#foo" ).one( "click", function() {
alert( "This will be displayed only once." );
});
等价于:
$("#foo").on("click", function(event){
alert("This will be displayed only once.");
$(this).off(event);
});