JQuery,为什么我的 mousemove 侦听器不传递事件对象?

JQuery, why won't my mousemove listener not pass the event object?

我正在使用以下代码。

var cursorXPos;
var cursorYPos;

$(document).mousemove( cursorLocation(evt) );

function cursorLocation (evt) {
 cursorXPos = evt.pageX;
 cursorYPos = evt.pageY;
}

但这给了我一个错误。

Uncaught TypeError: Cannot read property pageX of undefined.

但是,如果我使用匿名函数,事件对象会被传递,一切正常。

$(document).mousemove( function (evt) {
 cursorXPos = evt.pageX;
 cursorYPos = evt.pageY;
});

您需要将函数引用传递给 mousemove,不要调用它(通过添加 ()

$(document).mousemove( cursorLocation );

绑定事件时不能在函数中传递参数。您只需传递事件的名称,javascript 就会为您处理参数。

var cursorXPos;
var cursorYPos;

$(document).mousemove( cursorLocation ); // <-- here 

function cursorLocation (evt) {
    cursorXPos = evt.pageX;
    cursorYPos = evt.pageY;
}