【问题标题】:Can I pass more arguments into event handler functions in Javascript?我可以将更多参数传递给 Javascript 中的事件处理函数吗?
【发布时间】:2015-01-20 20:37:02
【问题描述】:

我一直在尝试了解更多有关鼠标事件的信息,例如 onmouseover、onmouseout 和 onmousemove,但没有太多信息。似乎这些事件处理程序默认只有一个参数,即事件本身。

element.onmouseover = mouseoverFunction

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

但是我希望能够将其他参数传递给函数。

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

如何将事件参数和附加参数传递给函数?

也可以将更多参数传递给事件处理函数吗?

【问题讨论】:

    标签: javascript event-handling


    【解决方案1】:

    你可以做一个高阶函数:

    function mouseover(arg1, arg2) {
      return function(event) {
        // Do stuff here
      }
    }
    
    element.addEventListener('mouseover', mouseover(1, 2))
    

    【讨论】:

    • 我确实看过,但发现它不受 IE8 及以下的支持
    • 寻找一个addEventListener polyfill,或者像你一样使用onmouseover 属性。
    • @elclanrs,我期待调用和应用方法。是否可以使用它们来做到这一点。如果我传入其他参数,我无法将事件传入函数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    • 2015-09-23
    • 2012-08-30
    相关资源
    最近更新 更多