事件绑定相对于交互页面是一个非常重要的一个技术,jQuery在事件绑定上面也做了很多。
目录
bind()
描述:为一个元素绑定一个事件,有三个参数,第一个为事件类型,第二个为处理函数,第三个是布尔值,当为false的时候,阻止冒泡,为true为冒泡事件。
$(function {
$('.box').bind('click',function(){
console.log(123);
})
})
同时bind()也可以绑定多个事件
$(function{
$('.box').bind("click mouseenter",function(){
console.log(123);
})
})
绑定多个事件显示不同内容,一对象的形式编写
$(function(){
$('.box').bind({
click : function(){
console.log(1);
},
mouseover : function(){
console.log(2);
}
})
})
delegate()
描述:事件委托。
3个参数 1 选择器 2时间类型 3处理函数
$(function() {
$('ul').delegate('li','click',function(){
console.log($(this).html());
})
})
on()
描述:为一个元素添加一个事件处理器,这个是最重要的,也是最常用的。
$(function (){
$('#btn').on('click',function(){
console.log(1);
})
})
它也可以写成事件委托
三个参数 1事件类型 2 事件源 3 执行函数
$('ul').on('click','li',function(){
console.log($(this).html());
})
同样也可以绑定多个事件。
$(function (){
$('p').on('mouseenter mouseleave' , function(){
console.log(123);
})
})
也可以绑定多个事件处理函数,以对象的形式
$(function(){
$('p').on({
click : function(){
console.log(123);
},
mouseenter : function(){
console.log(456);
},
})
})
off()
描述:移除事件,只能移除on事件绑定器绑定的时间
var handle = function(){
console.log(123);
}
$(function(){
$('div').on("click mouseover",'p',handle);
//移除mouseover事件
$('div').off('mouseover' , 'p' , handle );
//当off方法的参数都不写的时候。是移除所有事件
$('div').off();
});
one()
描述:为元素绑定事件,绑定的事件只能执行一次。
$(function(){
$('p').one('click', function(){
console.log(1);
})
})
unbind()
描述:bind()事件的移除事件
$(function(){
var handle = function(){
console.log(1);
}
$('p').bind('click',handle);
$('p').unbind('click' , handle);
})
undelegate()
描述:移除undelegete事件
$(function(){
var handle = function(){
console.log($(this).html());
}
$('div').delegate('p','click',handle);
$('div').undelegate('p' , 'click' , handle);
})