事件代理
事件代理就是在父级DOM元素绑定一个事件,当触发子级DOM元素的事件时,利用事件流的原理来触发绑定在父级DOM的事件。
demo:
<script>
$(function(){
function handle1(){
alert(1);
}
function handle2(){
alert(2);
}
//绑定
$('button:first').on('click',handle1);
$('button:first').on('click',handle2);
//解绑
$('button:last').on('click',function(){
$('button:first').off('click',handle2);
alert('解绑成功');
});
//事件代理
// $('ul').on({},'li'); li触发{}里面的事件
$('ul').on({
mouseover:function(){
//this指向li
$(this).css('background','teal');
},
mouseout:function(){
$(this).css('background','none');
}
},'li');
})
</script>
注:需导入jquery.min.js
jQuery事件
- 绑定
on('type',handle1)
on('type',handle2)
- 解绑
off('type') 解绑该类型所有的事件
off('type',handle) 解绑该事件类型对应的事件处理程序
- 模拟事件执行
trigger('type')
- 事件代理
$('ul').on({},'li')
$('ul').on({
mouseover:function(){
//this -->li
$(this).css();
},
mouseout:function(){
}
},'li')