Disable and enable jQuery context menu

后端 未结 2 547
面向向阳花
面向向阳花 2021-01-15 03:56

I use

$(\'#test\').unbind(\'click\');

to remove the click event on the #test item. How do I make the item clickable again?

Actual

相关标签:
2条回答
  • 2021-01-15 04:32

    Cache the handler to a variable. Then bind and unbind using that reference.

    Instead of binding your click event inline:

    $('#test').bind('click', function(){
        alert('hi!');
    });
    

    Declare the function to a variable:

    var clickHandle = function(){
        alert('hi!');
    };
    

    And then bind using the variable name:

    $('#test').bind('click', clickHandle);
    

    Then you can unbind the specific click handler:

    $('#test').unbind('click', clickHandle);
    

    Then you can still re-bind the same function:

    $('#test').bind('click', clickHandle);
    

    Took a quick look at the source. The event is bound to contextmenu, not click.

    You can access the function through the element's data.events property (similar to what j3frea was saying). Have a look at this fiddle example for a full resolution.

    Essentially you can do this:

    var cachedHandler = null;
    // disable
    cachedHandler = $('#demo2').data('events').contextmenu[0].handler;
    $('#demo2').unbind('contextmenu', cachedHandler);
    // enable
    $('#demo2').bind('contextmenu', cachedHandler);
    
    0 讨论(0)
  • 2021-01-15 04:35

    Take a look at this question Rebind DOM Event with jQuery

    Josiah's solution is preferable but if you really wanted to unbind the click event entirely I believe you could do this:

    var storedClick = $('#test').data('events').click[0].handler;
    $('#test').unbind('click');
    $('#test').bind('click', storedClick);
    

    Remember that data('events').click is an array so you would need to store the handler for every member of the array.

    0 讨论(0)
提交回复
热议问题