2012-04-09 175 views
0

尝试检测左击VS右键点击(不使用jQuery的!),我有以下代码我的mouseup代码有什么问题?

的Javascript:

function cclick(e) { 
    if (e.button == 1) {alert("hgbdygwea");} 
    else { 
     alert(e.button); 
    } 
} 

HTML:

<a onmouseup="cclick()" ...> <img .../> </a> <!-- also tried cclick instead of cclick() --> 

使用Internet Explorer 9

+0

什么问题?它检测到mouseup事件失败吗? – 2012-04-09 06:51:43

+0

它不警告,当我用HTML中的cclick替换cclick()时,它说.button是未定义的 – Oztaco 2012-04-09 06:52:41

+5

尝试'onmouseup =“cclick(event)”'。 – nnnnnn 2012-04-09 06:53:31

回答

3

您需要将事件对象传递给你的函数:

onmouseup="cclick(event);" 
0

以下是另一种方法

function cclick() { 
    var e = window.event; 
    if (e.button == 1) {alert("hgbdygwea");} 
    else { 
     alert(e.button); 
    } 
} 

并调用下面的函数,而没有经过event

<a onmouseup="cclick()" ...> <img .../> </a> 
+0

这只适用于Microsoft浏览器。其他浏览器没有window.event – Eric 2012-04-09 07:16:28

+1

当然,正如他所说的,他需要在'Internet Explorer 9' – prageeth 2012-04-09 07:38:18

0

我认为这段代码应该适合你。 e.button不适用于所有浏览器(并且我清理了代码)。

function cclick(e) { 
    "use strict"; 
    e || window.event; 
    if (e.which) { 
     alert((e.which === 1) ? "hgbdygwea" : e.which); 
    } else { 
     alert((e.button === 1) ? "hgbdygwea" : e.button); 
    } 
} 

<a onmouseup="cclick(event)" ...> <img .../> </a> <!-- also tried cclick instead of cclick() --> 
+0

上运行它,哪些浏览器是e.which的?我听说它是​​netscape,所以我不打扰它,因为它不再流行了? – Oztaco 2012-04-09 08:01:47