首页 新闻 赞助 找找看

jquery bind

0
悬赏园豆:5 [已解决问题] 解决于 2015-08-30 21:52
<div class="divs">
<div></div>
<div></div>
<div></div>
<div></div>
</div>

我想给class="divs"下面的每个div加个bind的点击事件,
然后点击当中的任何一个div的时候我想解除,除当前div以外的div的
bind事件,会有三秒的延时,等延时结束后其它div就恢复bind,这个怎么做
(简单说就是点击某个div禁用掉其它div的所以点击功能)
Mi文的主页 Mi文 | 初学一级 | 园豆:6
提问于:2015-06-15 15:37
< >
分享
最佳答案
0

(function() {
    var time = 3;
    var index = -1;
    $('.divs div').bind('click', function() {
        var _this = $(this);
        var thisIndex = $('.divs div').index(_this);
        if(time <= 0) {
            time = 3;
            index = -1;
        }
        if(index < 0) {
            index = thisIndex;
            timeCounter();
        }
        if(time > 0 && index != _this.index()) {
            return false;
        }
        //
        console.log(_this.text());
    });
    function timeCounter() {
        var start = setTimeout(function() {
            --time;
            if(time < 0) {
                clearTimeout(start);
                return false;
            }
            setTimeout(arguments.callee, 1000);
        }, 1000);
    }
})();

收获园豆:5
豆瓣绿 | 菜鸟二级 |园豆:237 | 2015-06-16 13:08
其他回答(2)
0
        $(window).load(function(){
            $(".divs div").bind("click",function(){
                var item=$(this);
                setTimeout(function(){
                $(".divs div").unbind("click");
                alert("移出其他事件");
                item.bind("click",function(){
                alert("只有我能点");
                })
                },3000);
            });
        });

HTML不变,将上面的代码加入js即可,我测试了,没问题。

TylorChen | 园豆:104 (初学一级) | 2015-06-15 17:45

 这样不行,取消unbind再bind就没效了

支持(0) 反对(0) Mi文 | 园豆:6 (初学一级) | 2015-06-16 09:45

@Mi文: 可以的吧,你只需要把第一次触发时间的Element用变量保存下来,我觉得应该好做吧~

支持(0) 反对(0) TylorChen | 园豆:104 (初学一级) | 2015-06-16 10:31
0

如果通过委托,则可以这样:

 

//通过事件委托来做(jQuery.fn.on)
var lockDiv;
$('.divs').on('click', 'div', function () {
    if (lockDiv != null && lockDiv != this) return;
    lockDiv = this;
    var self = $(this);
    alert('你点击的div的逻辑');
    setTimeout(function () {
        lockDiv = null;
    }, 3000);
});

 

考虑到性能,不要频繁的bind/unbind事件,通过在事件中判定是否禁止此次逻辑即可。

 

也可以这样:

//每个div绑定,适用于div各自事件逻辑不同
var cacheIndex = -1;
$('.divs>div').each(function (i) {
    $(this).on('click', function () {
        if (cacheIndex !== -1 && cacheIndex != i) {
            alert('你的逻辑');
            setTimeout(function () {
                cacheIndex = -1;
            });
        }
    });
});

多使用jQuery.fn.on少使用jQuery.fn.bind,jQuery.fn.bind API已被废弃(好像是在1.7之后)

 

 

linkFly | 园豆:91 (初学一级) | 2015-08-05 13:59
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册