【问题标题】:pass arguements to function called in addEventListener将参数传递给 addEventListener 中调用的函数
【发布时间】:2014-06-26 05:41:03
【问题描述】:

如果我像这样在 addEventListener 中调用函数:

document.querySelector('.elem').addEventListener('click', expand);

expand 函数接受参数。我怎样才能将这些参数传递给它?

我试过了

document.querySelector('.elem').addEventListener('click', expand(arg1, arg2, arg3));

但这不起作用。

【问题讨论】:

    标签: javascript


    【解决方案1】:

    使用匿名函数调用

    document.querySelector('.elem').addEventListener('click', function() {
        expand(arg1, arg2, arg3)
    }, false);
    

    如果您需要this 的值作为元素,您可以使用bind、apply 或call

    document.querySelector('.elem').addEventListener('click', function() {
        expand.apply(this, [arg1, arg2, arg3]);
    }, false);
    

    【讨论】:

    • 非常感谢!第二个正是我需要的!
    猜你喜欢
    • 2014-05-25
    • 2012-08-15
    • 1970-01-01
    • 2012-09-04
    • 2012-11-14
    • 2011-06-04
    • 2022-01-21
    • 2010-09-20
    相关资源
    最近更新 更多