How to pass arguments to addEventListener listener function?

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

    One way is doing this with an outer function:

    elem.addEventListener('click', (function(numCopy) {
      return function() {
        alert(numCopy)
      };
    })(num));
    

    This method of wrapping an anonymous function in parentheses and calling it right away is called an IIFE (Immediately-Invoked Function Expression)

    You can check an example with two parameters in http://codepen.io/froucher/pen/BoWwgz.

    catimg.addEventListener('click', (function(c, i){
      return function() {
        c.meows++;
        i.textContent = c.name + '\'s meows are: ' + c.meows;
      }
    })(cat, catmeows));
    

提交回复
热议问题