我有这样的问题:
 我有一个链接,单击该链接可在当前页面顶部的模式对话框中打开ajaxFormDialog。但是,当我单击中间按钮时,它在新选项卡中打开,并且所有内容都不在模式窗口中,而是当前在新选项卡页面上,看起来很糟糕。因此,我的问题是,如何禁用当前链接的鼠标中键单击?

<a class="ajaxFormDialog" ...></a>
<script>
    $(function (){
       $('a.ajaxFormDialog').live("click", function(e) {
           $.ajax({
                type: "POST",
                url: $("#formContent form").attr("action"),
                data: $("#formContent form").serialize(),
                success: function(data) {
                            //... do something
                         }
                 });
       });
</script>


UPD我用了你的建议

if(e.which == 2) {
   e.preventDefault();
}


它可能会阻止Default,但仍会使用该表单打开新标签页。
当我用链接上的中间/鼠标按钮单击时,它甚至没有显示我,他输入了此$(function(){$('a.ajaxFormDialog')。on(“ click”,function(e){.. 。

UPD2我写了这样的代码:

$(function (){
   $('a.ajaxFormDialog').live("click", function(e) {
       console.log("Which button is clicked: " + e.which);
       if(e.which == 2) {
          e.preventDefault();
       }
       // rest of the code...


因此,当我单击鼠标左键时,控制台会向我显示“单击了哪个按钮:1”,
但是当我单击鼠标中键/鼠标按钮时,它什么也没显示,仍然在新标签页中打开。

最佳答案

由于Firefox(并且可能还包括Opera)已经将中点点击行为从开发人员手中夺走了,因此,我建议使用其他节点(例如<span>)替换锚节点。

从语义上来说还可以,因为<a>标记在您的使用场景中不再充当实际链接。它可以使用CSS保持外观。

可以在此jsfiddle中找到一个实时示例。

对于这种标记:

<a class="ajaxFormDialog" href="#">replaced link</a>


您可以使用CSS,例如:

a, .ajaxFormDialog {
    color: orange;
    text-decoration: underline;
    cursor: hand;
}

a:hover, .ajaxFormDialog:hover {
    background: orange;
    color: white;

}


并用span替换锚,包括存储所需属性和维护任何子节点(如果有)的能力。您以后可以在事件处理程序中检索这些属性。

示例代码如下:

var genericHandler = function(e) {
    var el = $(e.target);
    var href = el.data('href');
    //extract data
    console.log('clicked span: ',el, ' with stored href: ', href);
    //do stuff here
};

$('a.ajaxFormDialog').replaceWith(function(){
    var el = $(this);
    console.log('replacing element: ', el);
    return $("<span>").addClass('ajaxFormDialog').append($(this).contents()).
        data('href', el.attr('href')). //you can store other data as well
        click(genericHandler);
});


如果您希望暂时避免点击中毒的副作用,那么这似乎是种种弊病。

关于javascript - 禁用鼠标中键进行模态对话框,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17234149/

10-14 17:10
查看更多