问题描述
大多数现代浏览器支持命令 ctrl +单击
或命令+单击
或类似于打开新链接选项卡或新窗口。
Most modern browsers support the commands ctrl+click
or command+click
or similar to open links in a new tab or a new window.
在应用程序中,我希望链接在单击时被禁用。但只是,如果目标是同一个窗口(例如,如果它在新选项卡中打开,我不希望该链接被禁用,因为再次点击它是合理的。)
In an application, I want the link to get disabled on clicking. But only, if the target is the same window (if it, for instance, opens in a new tab, I don't want the link to become disabled since it is reasonable to click it again).
我做了一些尝试并调试了在点击时创建的事件对象 - 但是我找不到有关目标是新标签页还是新窗口的任何信息。
I did some tries and debugged the event object that gets created on click - but I cannot find any information about whether the target is a new tab or a new window.
已知的解决方法:当然可以在点击特定链接时检查某个键是否被按下,这很简单 - 但由于这些命令因浏览器和操作系统而异,因此会有所不同必须定义一个复杂的映射,并确切地指出用户已配置的内容等等。
Known workaround: Certainly it is possible to check whether a certain key had been pressed while clicking a specific link, an easy thing - but since these commands vary from browser to browser and from OS to OS, one would have to define a complicated mapping and who nows exactly what the user has configured and so on.
是否有任何可靠的方法来确定是否应在新标签页或窗口?
Is there any reliable way of determining, whether the location should be opened in a new tab or window?
推荐答案
这里有一个工作示例:
Here you have a working example: http://jsfiddle.net/pioul/eCuNU/4/
只有在新的标签/窗口中打开链接时,此脚本才允许点击链接,基于 target =_ blank
属性。
This script will allow the click on the link only if the link is going to open in a new tab/window, based on the target="_blank"
attribute.
HTML:
<a href="http://google.fr" target="_blank">new window</a>
<a href="http://google.fr" target="_self">same window 1</a>
<a href="http://google.fr" target="">same window 2</a>
jQuery:
$("a").bind("click", function(e){
if($(this).attr("target") != "_blank"){
e.preventDefault();
}
});
编辑:
你可以考虑ctrl +点击这样:
You can take into account ctrl+clicks like this:
$("a").bind("click", function(e){
if($(this).attr("target") != "_blank"){
if(!e.ctrlKey){
e.preventDefault();
}
}
});
这篇关于确定点击链接是否打算打开新窗口或选项卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!