Javascript 触发右键单击

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6250447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:56:47  来源:igfitidea点击:

Trigger right-click

javascriptjquerycontextmenu

提问by glmxndr

I am trying to late-bind context menus to elements, using the ContextMenu plugin. So on the first right-click on those elements, I would like to :

我正在尝试使用ContextMenu 插件将上下文菜单后期绑定到元素。因此,在第一次右键单击这些元素时,我想:

  1. intercept the right-click through a live event on a certain "uncontextmenued" class,
  2. determine if the data('events').contextmenuexists,
  3. if not, attach the context-menu (and change the class to avoid re-throwing this live process),
  4. re-throw the right-click event to show the right-click.
  1. 通过某个“非上下文菜单”类上的实时事件拦截右键单击,
  2. 确定是否data('events').contextmenu存在,
  3. 如果没有,请附加上下文菜单(并更改类以避免重新抛出此实时进程),
  4. 重新抛出右键单击事件以显示右键单击。

I'm having trouble with the last item. jQuery allows to .click()or to .trigger('click'), which simulate a left-click, but there seems not to be a way to fire a right-click event through trigger.

我在处理最后一项时遇到了问题。jQuery 允许 to.click()或 to .trigger('click'),它模拟左键单击,但似乎没有办法通过 触发右键单击事件trigger

Or is there?

或者有吗?

回答by Niclas Sahlin

You can trigger it by

你可以通过

$('#element').trigger({
    type: 'mousedown',
    which: 3
});

http://api.jquery.com/trigger/#example-5

http://api.jquery.com/trigger/#example-5

回答by Ben Lesh

There is a newer way to do this:

有一种更新的方法可以做到这一点:

$('#element').triggerHandler('contextmenu');

Documentation can be found here.

文档可以在这里找到

回答by MacMac

Similar to this, but I'm not sure if you may be referring to jQuery UI data, but.

与此类似,但我不确定您是否指的是 jQuery UI 数据,但是。

$('#element').mousedown(function(event) 
{
    if(event.which == 3)
    {
        if(typeof($(this).data('events')) === 'undefined')
        {
            $(this).data('events', { somedata: 'hello' });
        }
        else
        {
            // "re-throw" right click context menu
        }
    }
});