How to pass arguments to addEventListener listener function?

前端 未结 30 2723
谎友^
谎友^ 2020-11-21 23:56

The situation is somewhat like-

var someVar = some_other_function();
someObj.addEventListener(\"click\", function(){
    some_function(someVar);
}, false);
<         


        
30条回答
  •  轮回少年
    2020-11-22 00:56

    This question is old but I thought I'd offer an alternative using ES5's .bind() - for posterity. :)

    function some_func(otherFunc, ev) {
        // magic happens
    }
    someObj.addEventListener("click", some_func.bind(null, some_other_func), false);
    

    Just be aware that you need to set up your listener function with the first param as the argument you're passing into bind (your other function) and the second param is now the event (instead of the first, as it would have been).

提交回复
热议问题