【小5说基础】jQuery 之on绑定事件以及off清除事件遇到的一些小坑吭,on被多次绑定,off如何清除

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位哦

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

全栈小5

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值