事件绑定
单个事件绑定
- 新的方法:$(selector).on(event,function) jquery1.7以前用bind()
- 传统方法:$(selector).event(function)
阻止事件冒泡:event.stopPropagation()
示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body >
<div>
<button id="bu" >点我</button>
</div>
<script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
<script>
$("#bu").click(function () {
$(this).css("background","blue")
})
$("#bu,body,div").on("click",function () {
alert("hello world")
event.stopPropagation()//如果没有这行代码,那么就将出现事件冒泡,点击按钮,将会有body,div,button都被触发事件,函数将会执行三次。
})
</script>
</body>
</html>
多个事件绑定
- $(selector).on({event:function,event:function…})
示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body >
<div id="bu">
点我
</div>
<script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
<script>
$("#bu").on({
mouseover:function () {
$(this).wrap("<h1></h1>")
},
mouseout:function () {
$(this).unwrap()
}
})
</script>
</body>
</html>
事件解绑
- $(seletor).off(event) 这里event如果省略,那么就解绑该元素的所有事件 jquery1.7以前用unbind()
示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body >
<div id="bu">
点我
</div>
<script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
<script>
$("#bu").click(function () {
alert("hello")
})
$("#bu").mouseover(function () {
alert("world")
})
$("#bu").off("mouseover")
</script>
</body>
</html>
事件绑定一次
- $(selector).one(event,function)
示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body >
<div id="bu">
点我
</div>
<script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
<script>
$("#bu").one("click",function () {
alert("hello")
})
</script>
</body>
</html>