2011-09-26 39 views
11

我目前正在设计一个简单的论坛应用程序。它主要由jQuery/AJAX驱动,并将所有内容加载到同一页面;然而,我知道有时候用户想要一次打开几个主题,在浏览论坛时在新标签中查看它们。jQuery:检测鼠标单击并在新标签中打开目标

我对此的解决方案是检测何时单击鼠标中键并单击鼠标左键,然后执行不同的操作。我想在点击鼠标左键时在窗口中加载AJAX的目标,否则将它加载到一个新的选项卡中。

我唯一的问题是我不知道用jQuery在新选项卡中打开目标位置的方法。很明显,不允许打开新选项卡,但有没有办法将这种类型的行为分配给用户生成的操作?

谢谢!

回答

15

请把眼光放在示例代码。它可以帮助

<script type='text/javascript'> 
    jQuery(function($){ 
     $('a').mousedown(function(event) { 
      switch (event.which) { 
       case 1: 
        //alert('Left mouse button pressed'); 
        $(this).attr('target','_self'); 
        break; 
       case 2: 
        //alert('Middle mouse button pressed'); 
        $(this).attr('target','_blank'); 
        break; 
       case 3: 
        //alert('Right mouse button pressed'); 
        $(this).attr('target','_blank'); 
        break; 
       default: 
        //alert('You have a strange mouse'); 
        $(this).attr('target','_self"'); 
      } 
     }); 
    }); 
</script> 
+1

单击链接时,是否会在执行操作之前更改目标属性? – Phillip

+0

是的,我会在动作之前更改属性。 –

+0

我想要当用户点击链接或打开一个新的标签。链接隐藏,但通过这些方式,它可能只在IE浏览器...我能做什么? –

0

中间鼠标按钮的默认操作是在新选项卡中打开。

您可以将超链接目标属性设置为_blank以打开新选项卡。

<a href="#link" target="_blank">Link</a> 

您也可以参考这个问题How to distinguish between left and right mouse click with jQuery

+0

我需要编辑我的问题,并使其更清楚。我正在通过左键单击加载AJAX目标,并在鼠标中键单击时打开新选项卡。 – Phillip

1
$('#element').mousedown(function(event) { 
      if(event.which == 3) { // right click 
       window.open("newlocation.html",""); 
      } 
    }); 

实时查看http://jsfiddle.net/8CHTm/1/

+0

@菲利普我添加了一个小提琴。 – Ehtesham

9
<a href="some url" target="_newtab">content of the anchor</a> 

在javascript中您可以使用

$('#element').mousedown(function(event) { 
     if(event.which == 3) { // right click 
      window.open('page.html','_newtab'); 
     } 
}) 
+0

啊我看到了,不知道我可以在window.open上设置目标属性。请试试这个。谢谢! – Phillip

+0

不用客气...................:D:D:D:D –

5

您还需要考虑键Ctrl和CMD-点击都用于打开新的选项卡(分别在windows/linux和mac中,因此,这将是一个更完整的解决方案:

jQuery.isClickEventRequestingNewTab = function(clickEvent) { 
    return clickEvent.metaKey || clickEvent.ctrlKey || clickEvent.which === 2; 
}; 
-1

请尝试 “_newTab” 而不是 “_blank”

window.open(URL, “_newtab”);