简体   繁体   中英

Whats wrong with my mouseup code?

Trying to detect left click vs right click (without using jQuery!) and I have the following code

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() -->

using inte.net explorer 9

You need to pass the event object to your function:

onmouseup="cclick(event);"

Quirksmode has a good write up on the subject of " Which mouse button has been clicked? " and his code works over the top of yours.

Following is another approach

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

And call the function as below without passing the event .

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

I think this code should work for you. e.button is not valid for all browsers (and I cleaned up the code).

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() -->

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM