jQuery事件绑定和解绑、事件冒泡与阻止事件冒泡及弹出应用示例

2020-05-24 21:40:57易采站长站整理

本文实例讲述了jQuery事件绑定和解绑、事件冒泡与阻止事件冒泡及弹出应用。分享给大家供大家参考,具体如下:

事件的绑定和解绑


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="../js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function () {
$('#div1').bind('mouseover click',function (event) {//绑定事件:移动到div块上和点击
alert($(this).html);
$(this).unbind('mouseover');//取消鼠标移动到上面的事件
})
})
</script>
<style type="text/css">
#div1{
background-color: #f6b544;
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<div id="div1">
</div>
</body>
</html>

绑定事件:移动到div块上和点击

解绑事件:取消鼠标移动到上面的事件

事件冒泡-阻止事件冒泡


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="../js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function () {
$('.son').click(function () {
alert(1);
});
$('.father').bind('click',function () {
alert(2);
});
$('.grandfather').bind('click',function () {
alert(3);
});
})
</script>
<style type="text/css">
.grandfather{
width: 300px;
height: 300px;
background-color: green;
}
.father{
width: 200px;
height: 200px;
background-color: gold;
}
.son{
width: 100px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<div class="grandfather">
<div class="father">
<div class="son">
</div>
</div>
</div>
</body>
</html>

定义了三个div,在son点击一下弹出1,father点击一下弹出2,grandfather点击一下弹出3,如果我们点击son一下,那么会依次弹出123,点击father一下会依次弹出二三。

按照标签往上传到它的父级

事件冒泡有时候不需要,需要阻止,通过

eventstopPropagation()
来阻止