为什么这个基本的JavaScript事件不起作用?

Kmo*_*sar -3 javascript events

试着用我目前非常有限的JavaScript知识来获得一些乐趣.

http://jsfiddle.net/pDMq9/

为什么这不起作用?我做错了什么?

HTML

<body>

<input type="button" value="Click me" id="button" />

</body>
Run Code Online (Sandbox Code Playgroud)

使用Javascript

var x = e.clientX;
var y = e.clientY;

var p = document.getElementById("button");

function mousedown() {
    if (p.mousedown) {
        alert(x, y);
    }
}
Run Code Online (Sandbox Code Playgroud)

Que*_*tin 8

  1. 您尝试从mousedown函数外部的事件中获取值(即在事件存在之前)
  2. You never assign the mousedown function as an event handler
  3. You don't accept any arguments to the mousedown function
  4. You test for a mousedown property inside the mousedown function for no apparent reason
  5. You pass multiple arguments to alert

So to fix it:

function mousedownHandler(e) {
    var x = e.clientX;
    var y = e.clientY;
    alert(x + ", " + y);
}

var p = document.getElementById("button");
p.addEventListener('mousedown', mousedownHandler);
Run Code Online (Sandbox Code Playgroud)