javascript “在新选项卡/窗口中打开”时的 .click() 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10774151/
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
.click() event when 'Open in new tab/window'
提问by Control Freak
When I use .click()
on an <a>
tag, the event only works when I click on the element. Otherwise, if the user does a Right Click > Open in new window or Open in new tab, it doesn't trigger the click()
event.
当我.click()
在<a>
标签上使用时,该事件仅在我单击该元素时起作用。否则,如果用户执行右键单击 > 在新窗口中打开或在新选项卡中打开,则不会触发该click()
事件。
So, my question is...how do I trigger the click()
event when user does right click > open in new tab/window?
所以,我的问题是......click()
当用户右键单击> 在新选项卡/窗口中打开时如何触发事件?
Here is the HTML:
这是 HTML:
<a href="url">Click Me</a>
Here is the Js:
这是Js:
$("a").click(function(){
alert('You clicked me!');
});
采纳答案by Danilo Valente
You can try this code, but remember that changing the UI is not a good ideia:
你可以试试这个代码,但记住改变 UI 不是一个好主意:
var addEvent = (document.addEventListener) ?
function(target,event,fn){
if(target) return target.addEventListener(event,fn,false);
}:
function(target,event,fn){
if(target) return target.attachEvent(('on' + event),fn);
},
allLinks = document.links || document.getElementsByTagName('a');
for(var i=0;i<allLinks.length;i++)
addEvent(allLinks[i],'mouseup',function(e){
var e = e || event;
if(e.which===3){
alert('Open in new tab/window');
e.preventDefault();
return false;
}
});