Can I pass more arguments into event handler functions in Javascript?

微笑、不失礼 提交于 2019-12-25 18:52:51

问题


I have been trying to find out more about mouse events such as onmouseover, onmouseout and onmousemove but there is not much info. It seems these event handlers by default have a single argument, the event its self.

element.onmouseover = mouseoverFunction

function mouseoverFunction( event ) {
    // Do stuff here
}

However I want to be able to pass other arguments to into the function.

function mouseoverFunction( event, moreArgs ) {
    // Do stuff here
}

How do I pass the event argument and additional arguments to the function?

Also is it ok to pass more arguments into an event handler function?


回答1:


You can make a higher-order function:

function mouseover(arg1, arg2) {
  return function(event) {
    // Do stuff here
  }
}

element.addEventListener('mouseover', mouseover(1, 2))


来源:https://stackoverflow.com/questions/28054692/can-i-pass-more-arguments-into-event-handler-functions-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!