Removing event handler with .off

China☆狼群 提交于 2019-12-08 06:56:42

问题


I am unable to remove the event handler using .off for the boxes.

Once a box is clicked I need the event handler removed for that box, currently I have made the hook ".clickable" and remove the class and tried to remove the event handler then apply the event handler back to all boxes with a class of ".box".

        $('.clickable').off('click','**').on("click", function(event){

        if( !$('.box').is(':animated') ) {

            var position = $(this).position()
            ,   targetPosition =  $('.target').position();

            $(this)
                .clone() //clone element
                .addClass('cloned') //add class to cloned element
                .css({
                    'position' : 'absolute'
                ,   'top' : position.top 
                ,   'left' : position.left 
                })
                .appendTo('body'); //append to the document

                animate(position,targetPosition);

                $(this)
                    .removeClass('clickable')
                    .addClass('notActive');

        };

    });

Thanks everyone for your advice and help, if anyone would like to see the final demo "working" here is a fiddle

working version


回答1:


Correction for your code, haven't tested but should work

$(document).on("click", '.clickable', function(event){
    if( !$('.box').is(':animated') ) {
        var position = $(this).position();
        var targetPosition =  $('.target').position();
        $(this)
            .clone() //clone element
            .addClass('cloned') //add class to cloned element
            .css({
                'position' : 'absolute'
            ,   'top' : position.top 
            ,   'left' : position.left 
            })
            .appendTo('body'); //append to the document
            animate(position,targetPosition);
            $(this)
                .removeClass('clickable')
                .addClass('notActive')
                .off('click');
    };
}); 


来源:https://stackoverflow.com/questions/16088400/removing-event-handler-with-off

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!