【问题标题】:JQuery, why won't my mousemove listener not pass the event object?JQuery,为什么我的 mousemove 侦听器不传递事件对象?
【发布时间】:2015-08-12 11:09:50
【问题描述】:

我正在使用以下代码。

var cursorXPos;
var cursorYPos;

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

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

但这给了我一个错误。

未捕获的类型错误:无法读取未定义的属性pageX

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

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

【问题讨论】:

  • 第一个 sn-p 执行cursorLocation,然后使用它的返回值作为对实际事件处理程序的引用。您没有返回任何内容,因此引用将是 undefined

标签: javascript jquery events mouseevent mousemove


【解决方案1】:

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

$(document).mousemove( cursorLocation );

【讨论】:

  • 妈的,比我快 20 秒 :)
【解决方案2】:

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

var cursorXPos;
var cursorYPos;

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

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

【讨论】:

  • @arun-p-johny 感谢你们的帮助。它现在正在工作。我很好奇如果函数有多个参数会发生什么,javascript如何知道将事件对象传递给哪个参数?
  • 如果您指的是 jQuery 事件中使用的函数,例如,jQuery 将事件传播到您指定的函数,因此它们(几乎)总是在每次调用时提供 (event, ui) 参数。您还可以使用 (foo, bar) 等自定义名称定义您的方法,在这种情况下,foo 将只是带有另一个名称的 event 参数。
  • 假设我的方法有参数(foo、bar、name)。我假设 event 和 ui 始终是事件处理程序传递的第一个对象,因此它们将占用 foo 和 bar。但是我将如何传递名称对象?
  • 抱歉回答迟了。你可以像this pastie 那样做。当你用 jQuery 绑定事件时,函数总是锁定到 2 个参数。
猜你喜欢
  • 2011-03-31
  • 1970-01-01
  • 2015-12-07
  • 1970-01-01
  • 2020-04-18
  • 2016-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多