禁用并启用jQuery上下文菜单 [英] Disable and enable jQuery context menu
问题描述
我使用
$('#test').unbind('click');
删除#test项目上的点击事件。如何使项目再次可点击?
to remove the click event on the #test item. How do I make the item clickable again?
实际上我有一张桌子。在单击事件上,将显示上下文菜单。但如果没有条目,则必须禁用菜单。所以我在上面使用unbind。由于上下文菜单是由插件生成的,我不知道如何让它再次点击。
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.
任何想法?
更新:这是设置上下文菜单的方式
Update: this is how the context menu is set up
$('#contacts tbody tr').contextMenu('myMenu1', {
bindings: {
'sms': function(t) {},
'delete': function(t) {}
}
});
由于我仍然不确定如何解决我的问题,我会再详细描述一下。我在jQuery中使用轻量级上下文菜单插件来显示上下文菜单。
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
是表格行, myMenu1
是tr点击时出现的上下文菜单。
are the table rows and myMenu1
is the context menu that appears on tr click.
在我的页面上,我有一张桌子。每一行都有自己的上下文菜单,总是相同,但 function(t)
总是对点击的行进行引用。
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.
而不是将您的click事件内联绑定:
Instead of binding your click event inline:
$('#test').bind('click', function(){
alert('hi!');
});
将函数声明为变量:
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);
快速查看来源。事件绑定到contextmenu,而不是单击。
Took a quick look at the source. The event is bound to contextmenu, not click.
您可以通过元素的data.events属性访问该函数(类似于j3frea所说的)。请查看此小提琴示例以获得完整分辨率。
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.
基本上你可以这样做:
var cachedHandler = null;
// disable
cachedHandler = $('#demo2').data('events').contextmenu[0].handler;
$('#demo2').unbind('contextmenu', cachedHandler);
// enable
$('#demo2').bind('contextmenu', cachedHandler);
这篇关于禁用并启用jQuery上下文菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!