事件处理on()绑定事件
on(方法在匹配元素上绑定一个或多个事件的事件处理函数
语法:
element.on (events,[selector],fn)
1.events:一个或多个用空格分隔的事件类型,如"click"或"keydown”.
2.selector:元素的子元素选择器。
3.fn:回调函数
案例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/jquery-3.5.1.min.js"></script>
<style>
div{
width: 200px;
height: 200px;
background-color: blue;
}
</style>
</head>
<body>
<div>
</div>
<script>
/*单个事件注册*/
// $('div').click(function () {
// $(this).css('backgroundColor', 'pink');
// })
// $('div').mouseenter(function () {
// $(this).css('backgroundColor', 'purple');
// })
/*多个事件注册*/
$('div').on({
mouseenter: function () {
$(this).css('backgroundColor', 'purple');
}, click: function () {
$(this).css('backgroundColor', 'pink');
}, mouseleave: function () {
$(this).css('backgroundColor', 'blue');
}
})
</script>
</body>
</html>
如果多个事件回调函数相同:
$('div').on('mouseleave mouseenter', function () {
$(this).toggleClass('current');
})
事件委托:(绑定父元素,点击子元素触发)
/*事件委托*/
$('ul').on('click', 'li', function () {
alert('11');
})
为后加入的元素绑定事件
/*动态创建*/
$('ol lo').click(function () {
alert('11'); //不可以为后来的元素绑定事件
})
$('ol lo').on('click',function () {
alert('11'); //可以为未来创建的元素绑定事件
})
var li = $('<li>后来的li</li>')
$('ol').append(li);