# 4.jQuery事件
# 4.1 事件注册
# 单个事件注册
语法:
element.事件(function () {})
$('div').click(function () {
console.log('div被点击啦!');
$(this).css('backgroundColor','blue');
})
其事件和原生基本一致
比如:mouseover、mouseout、blur、focus、change、keydown、keyup、resize、scroll等
# 4.2 事件处理
# 4.2.1 on() 绑定事件
on() 方法在匹配元素上绑定一个或多个事件的事件处理函数
element.on(events, [selector], fn);
- events:一个或多个用空格风格的事件类型,如'click' 'keydown'
- selector:元素的子元素选择器
- fn:回调函数
$('div').on({
click: function () {
console.log('div被点击啦!');
$(this).css('backgroundColor','blue');
},
mouseenter: function () {
console.lg('鼠标进入div啦!');
$('this').css('backgroundColor','red');
}
})
$('div').on('mouseenter mouseleave',function () {
$(this).toggleClass('box');
})
事件委派:
$('ul').on('click','li',function () {
console.log('li被点击了')
})
优势:
- 可以绑定多个事件、多个处理事件处理程序
- 可以事件委派操作。事件委派的定义就是,把原来加给子元素身上的事件绑定在父元素身上,就是把事件委派给父元素
- 动态创建的元素,click()没有办法绑定事件,on()可以给动态生成的元素绑定事件
# 4.2.2 off() 解绑事件
off() 方法可以移除通过on()方法添加的事件处理程序
element.off(events, [selector]);
$('div').on({
click: function () {
console.log('div被点击啦!');
$(this).css('backgroundColor','blue');
},
mouseenter: function () {
console.lg('鼠标进入div啦!');
$('this').css('backgroundColor','red');
}
})
$('div').off(); // 全部解绑
$('div').off('click'); // 解绑click事件
$('ul').off('click','li'); // 解绑事件委托
# 4.2.3 one()绑定
one()绑定的事件,只触发一次
$('div').one('click',function(){
console.log('这个点击事件只触发一次');
})
# 4.2.4 自动触发事件
元素.事件()
element.trigger('type')
element.triggerHandler(type)
不会触发元素的默认行为——比如输入框的focus等
$('div').on('click',function(){
console.log('div被点击');
})
$('div').click(); // 刷新页面时,click事件就被触发
$('div').trigger('click');
$('div').triggerHandler('click');
# 4.3 jQuery 事件对象
时间被触发,就会有事件对象的产生
element.on(events, [selector], function (event) {})
阻止默认行为: event.preventDefault() 或 return false
阻止冒泡: event.stopPropagation()
$(document).on('click',function(){
console.log('document被点击');
})
$('div').on('click',function(event){
console.log('div被点击');
event.stopPropagation();
})