如何防止用户中间点击带有javascript或jquery的链接 [英] How can I prevent a user from middle clicking a link with javascript or jquery

查看:75
本文介绍了如何防止用户中间点击带有javascript或jquery的链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想阻止用户单击中间链接以打开新标签.我尝试了以下方法:

I want to prevent the user from being able to middle click a certain link to open a new tab. I have tried the following:

$(window).on('mouseup', '.sptDetails', function(e){
    e.preventDefault();
    if(e.button == 1){
        return false;
    }
});

这似乎不起作用.

推荐答案

这是jQuery和浏览器的不幸组合.为了防止打开新选项卡,您必须使用click事件(而不是mouseup),但是使用jQuery

It's an unfortunate combination of jQuery and the browser. To prevent the new tab from opening you have to use the click event (rather than mouseup), but jQuery does not run delegate click handlers for mouse buttons other than the left one:

// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && !(event.button && event.type === "click") ) {

您可以使用非委托处理程序,并亲自检查目标元素: http://jsbin.com/ojoqap/10/edit .至少在Chrome上有效(受@Abraham启发).

What you can do is using a non-delegate handler and check the target element yourself: http://jsbin.com/ojoqap/10/edit. This works on Chrome, at least (inspired by @Abraham).

$(document).on("click", function(e) {
  if($(e.target).is("a[href]") && e.button === 1) {
    e.preventDefault();
  }
});

这篇关于如何防止用户中间点击带有javascript或jquery的链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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