第二次单击按钮

时间:2015-02-07 11:23:13

标签: javascript jquery backbone.js click

我遇到了一些问题,当我点击按钮时,“工具栏”附加到正文,当我再次点击按钮时,“工具栏”会再次附加到正文。单击按钮时如何删除重复的事件?巨大的thx!

var Link = function(collection, el){
    el.on('mouseup', function(e){
        $('[el-button]').click(function(e){
            e.preventDefault();
        });

        var _toolbar = new Toolbar({link: el});
        var toolbar  = _toolbar.render();
        toolbar.addClass('in');
        $('body').prepend(toolbar);

        toolbar.css({
            left: el.offset().left,
            top: el.offset().top - toolbar.height() - 10  
        });

        setTimeout(function(){
            $(document).on('mouseup', function(e){
                if($(e.target).closest(toolbar).length == 0){
                    $(el).unbind('click', arguments.callee);
                        toolbar.removeClass('in');
                        toolbar.remove();
                }
            });
        }, 100);
    });

    el.bind('linkChange', function(){
        var section = el.parents('section');
        var index   = section.index();
        var model   = collection.at(index);
        model.set(Helper.sectionToObj(section))
    });
}

return Link;

现在如何运作:http://take.ms/b5giM

3 个答案:

答案 0 :(得分:3)

尝试.one() - 它只执行一次。 jQuery documentation for one

el.one('mouseup', function(e){

答案 1 :(得分:0)

这个问题已经得到了埃文的好答案,这是另一种方法

尝试这样的事情,

$(".idofbutton").click(function(){
    //your work 


    // after finishing your work unbind the click handler for only this button
    $(this).unbind('click');
}

答案 2 :(得分:0)

根据页面上的答案和评论,我建议:

el.mouseup(function(e){
    $('[el-button]').click(function(e){
        e.preventDefault();
    });

    if (($this).prev(".in").length == 0) {

    var _toolbar = new Toolbar({link: el});
    var toolbar  = _toolbar.render();
    toolbar.addClass('in');
    $('body').prepend(toolbar);

    toolbar.css({
        left: el.offset().left,
        top: el.offset().top - toolbar.height() - 10  
    });

    setTimeout(function(){
        $(document).on('mouseup', function(e){
            if($(e.target).closest(toolbar).length == 0){
                $(el).unbind('click', arguments.callee);
                    toolbar.removeClass('in');
                    toolbar.remove();
            }
        });
    }, 100);
   }
});

元素工具栏有一个名为in的类名。我不知道该元素的进一步标记,所以你可以改变它。如果页面上有一个先前的兄弟(在元素el之前),并且类名为in,则不执行代码。