jQuery只允许在某些元素上使用contextmenu [英] jQuery allow contextmenu only on certain elements

查看:95
本文介绍了jQuery只允许在某些元素上使用contextmenu的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


// this works

$(document).on('contextmenu', function() {
    return false;
});


// without the code above, this works too

$(document).on('contextmenu', '#special', function() {
    alert('#special right clicked');
});

如何结合这两段代码,以便可以禁用整个文档的上下文菜单,除了ID为#special的代码.

How can I combine these 2 pieces of code so that I can disable context menu on the whole document except the one with id #special.

推荐答案

$(document).on('contextmenu', function(e) {
    if (!$(e.target).is("#special"))
       return false;

    alert('#special right clicked');
    // you may want e.preventDefault() here
});

使用 .is()方法,您可以测试单击的元素是否与任何选择器匹配,这基本上就是您最初委派的选择器.on()调用确实在幕后进行,但是如果您要专门检查元素ID,则说起来会更有效:

Using the .is() method lets you test whether the clicked element matches any selector, which is basically what your original delegated .on() call did behind the scenes, but if you're checking for an element id specifically it would be more efficient to say:

if (e.target.id != "special")
    return false;

这篇关于jQuery只允许在某些元素上使用contextmenu的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆