开发者

Disable and enable jQuery context menu

I use

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

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

Actually I have a table. On click event a context menu appears. But if there are no entries the menu has to be disabled. So I use unbind above. Since the context menu is generated by a plugin I do not know how to make it clickable again.

Any ideas?

Update: this is how the context menu is set up

 $('#contacts tbody tr').contextMenu('myMenu1', {
    bindings: {
      'sms': function(t) {},
      'delete': function(t) {}
    } 
 });

Since I am still not sure how to solve my problem I will describe it a little more. I use the lightweight context-menu plugin in jQuery to display context menus.

#contacts tbody tr 

are the table rows and myMenu1 is the context menu that appears on tr click.

On my page I have a table. Each row has its own开发者_如何学运维 context menu, well always the same but function(t) referes always to the clicked row.

Well, the table may be empty so I want to disable the context menu. I believe there are may ways to do that. One is to unbind the click event, this does not work for me.

I hope anyone has an idea.


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);


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜