您的位置:首页 > Web前端 > JQuery

jquery 深入学习笔记之一 (事件绑定)

2015-07-27 10:44 686 查看
【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);
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: