鼠标上的onClick()和中间按钮问题

时间:2010-07-17 18:23:58

标签: jquery javascript-events onclick

<a href="<?=$rowz[0]?>" onClick="countLinks('<?=$row[6]?>','<?=$indexl?>')">[Link <?=$j++?>]</a>

问题是它无法在IE或Firefox上使用中键。 实际上,countLinks使用中间按钮仅使用chrome调用。

我想我需要一个类似mouseup事件的Jquery函数,只是我不知道如何使用这些参数调用该函数调用countLinks

任何帮助?

3 个答案:

答案 0 :(得分:6)

你是对的。您需要mousedownmouseup事件来确定实际点击了哪个鼠标按钮。

但首先,您需要摆脱内联事件处理程序onclick,并遵循不显眼的javascript 的光辉之路。

因为您需要为该锚点添加idclass标记来识别它(当然您也可以选择使用css选择器选择该锚点)。假设我们添加了一个名为 myClazzz 的类:)

的javascript:

$(function(){
    $('.myClazzz').bind('mouseup', function(e){
        switch(e.which){
           case 1:
              alert('Left Mouse button pressed.');
           break;
           case 2:
              alert('Middle Mouse button pressed.');
           break;
           case 3:
              alert('Right Mouse button pressed.');
           break;
           default:
              alert('You have a strange Mouse!');
        }
    });
});

which / mousedown事件处理程序中的mouseup属性将包含一个数字,表示单击了哪个鼠标按钮。

答案 1 :(得分:2)

这是一个快速的解决方案,通过使用一些html5 attributes ...实际上它也可能在html5之前,但它没有验证。

我会创建如下链接:

<a class="myClazzz" href="<?=$rowz[0]?>" data-row="<?=$row[6]?>" data-index="<?=$indexl?>">...</a>

_我们将您的参数设置为data属性

并写下这样的js:

$(function(){
    //use mouseup, then it doesn't matter which button 
    //is clicked it will just fire the function
    $('.myClazzz').bind('mouseup', function(e){
        //get your params from data attributes
        var row   = $(this).attr("data-row"),
            index = $(this).attr("data-index");

        //and fire the function upon click
        countLinks(row,index);
    });
});
//don't forget to include jquery, before these lines;)

希望这会成功。思南。

PS myClazzz - &gt;学分转到jAndy:)

答案 2 :(得分:1)

浏览器的行为变化很大。见https://code.google.com/p/chromium/issues/detail?id=255#c106。根据你所问的那些:

  • &#34;如果目标是链接,IE不会触发点击事件,但如果目标是链接,则触发它 即使它是链接的后代,也会点击另一个元素。&#34;

  • &#34; Gecko总是在文件上触发点击事件,该事件起泡并具有 定位被点击的元素。&#34;

对于Firefox,您可以这样做:

$( document ).click(
  function ( evt ) {
    // ... evt.which === 2 means middle click
  }
);

这是一种技巧(通常你会听到链接本身的事件),但它确实有效。