-----------------------------------题记
最近项目需求:点击出现一个块,再次点击消失,继续点击关闭,并且点击空白处该块消失。那么在这个在这个功能的完成中,因情况需要使用到了live和bind两种事件绑定功能,而使用这两种事件绑定的标签存在父子关系,然后,在测试的过程中控制事件传播的时候出现了些状况,使用event.stopPropagation()在子标签事件处还是在父标签事件处是根据该事件传播是冒泡还是捕捉(冒泡:如单击子标签,那么先触发子标签的click事件,再依次触发父标签的click事件。捕捉:相反。)。所以浪费了大量的事件才调试好,最后还是不明白是什么情况,于是就做出了如下的测试。
-----------------------------------代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<script type="text/javascript" src="jquery-1.8.2.js"></script>
<script type="text/javascript">
$(function() {
//使用live添加事件时,不能使用父子关系进行绑定
// $("#child").live("click", function(event) {
// alert("child");
// });
// $("#child").parents("div").live("click", function(event) {
// alert("parent");
// });
//使用bind添加事件时,可以使用父子关系进行绑定
$("#parent").bind("click", function(event) {
alert("parent");
});
$("#parent").children().bind("click", function(event) {
// event.stopPropagation();//冒泡在child处停止事件传播
alert("child");
});
//两bind
$("#one-p").bind("click", function(event) {
alert("parent");
});
$("#one-c").bind("click", function(event) {
// event.stopPropagation();//冒泡在child处停止事件传播
alert("child");
});
//两live
$("#two-p").live("click", function(event) {
alert("parent");
});
$("#two-c").live("click", function(event) {
// event.stopPropagation();//冒泡在child处停止事件传播
alert("child");
});
//父live子bind
$("#three-p").live("click", function(event) {
alert("parent");
});
$("#three-c").bind("click", function(event) {
// event.stopPropagation();//冒泡在child处停止事件传播
alert("child");
});
//父bind子live
$("#four-p").bind("click", function(event) {
// event.stopPropagation();//捕获在parent处停止事件传播
alert("parent");
});
$("#four-c").live("click", function(event) {
alert("child");
});
});
</script>
<body>
<div id="parent">
<input id="child" type="button" value="click" />
</div>
<div id="one-p">
<input id="one-c" type="button" value="click" />
<span>parent -> bind & child -> bind ==> 冒泡</span>
</div>
<div id="two-p">
<input id="two-c" type="button" value="click" />
<span>parent -> live & child -> live ==> 冒泡</span>
</div>
<div id="three-p">
<input id="three-c" type="button" value="click" />
<span>parent -> live & child -> bind ==> 冒泡</span>
</div>
<div id="four-p">
<input id="four-c" type="button" value="click" />
<span>parent -> bind & child -> live ==> 捕获</span>
</div>
</body></html>
-----------------------------------总结
1.使用live绑定事件的时候,不能利用操作父子关系来绑定标签的事件。
2.标签存在父子关系的时候:只有再父标签为bind,子标签为live的时候事件传播为捕获。那么在事件传播为捕获的话只能在父标签绑定的事件处停止事件的传播,相反为冒泡的话,则在子标签绑定的事件处停止事件的传播。