How to pass arguments to addEventListener listener function?

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

The situation is somewhat like-

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


        
30条回答
  •  萌比男神i
    2020-11-22 00:42

    The following approach worked well for me. Modified from here.

    function callback(theVar) {
      return function() {
        theVar();
      }
    }
    
    function some_other_function() {
      document.body.innerHTML += "made it.";
    }
    
    var someVar = some_other_function;
    document.getElementById('button').addEventListener('click', callback(someVar));
    
    
      
        
      
    

提交回复
热议问题