1.jQuery 事件注册
jQuery 为我们提供了方便的事件注册机制,使开发人员易于操作,优缺点如下:
- 优点:操作简单,且不用担心事件覆盖等问题。
- 缺点:普通的事件注册不能做事件委托,且无法实现事件绑定,需要借助其它方法。
演示代码:
<body>
<div></div>
<script>
$(function() {
// 1. 单个事件注册
$("div").click(function() {
$(this).css("background", "purple");
});
$("div").mouseenter(function() {
$(this).css("background", "skyblue");
});
})
</script>
</body>
2.jQuery 事件处理
因为普通注册事件方法的不足,jQuery 又开发了多个处理方法,重点讲解如下:
- on():用于事件绑定,也是目前最好用的事件绑定方法
- off():事件解绑
- trigger() / triggerHandler():事件触发。
2.1 事件处理 on() 绑定事件
因为普通注册事件方法不足,jQuery 又创建了多个新的事件绑定方法 bind() / live() / delegate() / on() 等,其中最好用的是 on()。
演示代码:
<style>
div{
width: 100px;
height: 100px;
background-color: pink;
}
.current {
background-color: purple;
}
</style>
<script src="jquery.min.js"></script>
</head>
<body>
<div></div>
<script>
$(function() {
// 1.单个事件注册
// $("div").click(function() {
// $(this).css("background", "purple");
// })
// $("div").mouseenter(function() {
// $(this).css("background", "skyblue");
// })
// 2.事件处理 on
// (1) 使用 on 绑定多个事件
// $("div").on({
// mouseenter: function() {
// $(this).css("background", "skyblue");
// },
// click: function() {
// $(this).css("background", "purple");
// },
// mouseleave: function() {
// $(this).css("background", "blue");
// }
// })
$("div").on("mouseenter mouseleave", function() {
$(this).toggleClass("current");
})
})
</script>
演