1.1 单个事件注册
$(“div”).click(function(){ 事件处理程序 })
1.2 on() 绑定事件
on() 方法在匹配元素上绑定一个或多个事件的事件处理函数
1.3 off() 解绑事件
off() 方法可以移除通过 on() 方法添加的事件处理程序。
1.4 demo
绑定DEMO:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
div {
width: 100px;
height: 100px;
background-color: pink;
}
.current {
background-color: purple;
}
</style>
<script src="jquery.min.js"></script>
</head>
<body>
<div></div>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<ol>
</ol>
<script>
$(function() {
// 1. 单个事件注册
// $("div").click(function() {
// $(this).css("background", "purple");
// });
// $("div").mouseenter(function() {
// $(this).css("background", "skyblue");
// });
// 2. 事件处理on
// on可以绑定1个或者多个事件处理程序
// $("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");
});
// (2) on可以实现事件委托(委派)
// $("ul li").click();
$("ul").on("click", "li", function() {
alert(11);
});
// click 是绑定在ul 身上的,但是 触发的对象是 ul 里面的小li
// (3) on可以给未来动态创建的元素绑定事件
// $("ol li").click(function() {
// alert(11);
// })
$("ol").on("click", "li", function() {
alert(11);
})
var li = $("<li>我是后来创建的</li>");
$("ol").append(li);
})
</script>
</body>
</html>
解绑demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
div {
width: 100px;
height: 100px;
background-color: pink;
}
</style>
<script src="jquery.min.js"></script>
<script>
$(function() {
$("div").on({
click: function() {
console.log("点击了");
},
mouseover: function() {
console.log('鼠标经过了');
}
});
$("ul").on("click", "li", function() {
alert(11);
});
// 1. 事件解绑 off
// $("div").off(); // 这个是解除了div身上的所有事件
$("div").off("click"); // 这个是解除了div身上的点击事件
$("ul").off("click", "li");
// 2. one() 但是它只能触发事件一次
$("p").one("click", function() {
alert(11);
})
})
</script>
</head>
<body>
<div></div>
<ul>
<li>我们都是好孩子</li>
<li>我们都是好孩子</li>
<li>我们都是好孩子</li>
</ul>
<p>我是Echo</p>
</body>
</html>