How to pass arguments to addEventListener listener function?

前端 未结 30 2321
谎友^
谎友^ 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:32

    There is absolutely nothing wrong with the code you've written. Both some_function and someVar should be accessible, in case they were available in the context where anonymous

    function() { some_function(someVar); } 
    

    was created.

    Check if the alert gives you the value you've been looking for, be sure it will be accessible in the scope of anonymous function (unless you have more code that operates on the same someVar variable next to the call to addEventListener)

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

提交回复
热议问题