jquery 事件处理

事件处理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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值