1、模拟点击div#test绑定div.test的click事件,代码如下
描述:点击多少次A区域,然后再点击B区域就会出发多少次click事件,比如我点击了两次A区域,那么再点击一次B区域,就会弹出两次alert
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<div style="margin-top:50px;"></div>
<div id="test" style="display:inline-block;padding:10px 20px;background:#099dff;color:#fff;">
点击绑定当前区域
</div>
<div class="test" style="display:inline-block;padding:10px 20px;background:#099dff;color:#fff;">测试区域</div>
<script type="text/javascript">
$("#test").click(function () {
$("body").on("click", ".test", function () {
alert("test");
});
});
</script>
2、on绑定事件记住顺序
1)错误格式:$("div").on("click",".test",function(){});
这样绑定也是无效的,虽然click和test位置对了,但是div区域无效,具体没仔细研究
2)错误格式:$("body").on(".test","click",function(){});
on的第一个参数一定是事件名称,否则无效
3)正确格式:$("body").on("click",".test",function(){});
3、off清除on绑定的方法
格式:$("body").off(".test","click");
对上面的代码可以更改如下
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<div style="margin-top:50px;"></div>
<div id="test" style="display:inline-block;padding:10px 20px;background:#099dff;color:#fff;">
A区域
</div>
<div class="test" style="display:inline-block;padding:10px 20px;background:#099dff;color:#fff;">B区域</div>
<script type="text/javascript">
$("#test").click(function () {
$("body").off("click", ".test").on("click", ".test", function () {
alert("test");
});
});
</script>
关注小程序:一句话一感想一心情,时时刻刻书写你的一句话,还有机会上C位哦