How to pass arguments to addEventListener listener function?

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

    You need:

    newElem.addEventListener('click', {
        handleEvent: function (event) {
            clickImg(parameter);
        }
    });
    
    0 讨论(0)
  • 2020-11-22 00:53

    nice one line alternative

    element.addEventListener('dragstart',(evt) => onDragStart(param1, param2, param3, evt));
    
    function onDragStart(param1, param2, param3, evt) {
    
     //some action...
    
    }
    
    0 讨论(0)
  • 2020-11-22 00:54

    Use

       el.addEventListener('click',
        function(){
            // this will give you the id value 
            alert(this.id);    
        },
    false);
    

    And if you want to pass any custom value into this anonymous function then the easiest way to do it is

     // this will dynamically create property a property
     // you can create anything like el.<your  variable>
     el.myvalue = "hello world";
     el.addEventListener('click',
        function(){
            //this will show you the myvalue 
            alert(el.myvalue);
            // this will give you the id value 
            alert(this.id);    
        },
    false);
    

    Works perfectly in my project. Hope this will help

    0 讨论(0)
  • 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));
    
    0 讨论(0)
  • 2020-11-22 00:54

    There is a special variable inside all functions: arguments. You can pass your parameters as anonymous parameters and access them (by order) through the arguments variable.

    Example:

    var someVar = some_other_function();
    someObj.addEventListener("click", function(someVar){
        some_function(arguments[0]);
    }, false);
    
    0 讨论(0)
  • 2020-11-22 00:55

    You can just bind all necessary arguments with 'bind':

    root.addEventListener('click', myPrettyHandler.bind(null, event, arg1, ... ));
    

    In this way you'll always get the event, arg1, and other stuff passed to myPrettyHandler.

    http://passy.svbtle.com/partial-application-in-javascript-using-bind

    0 讨论(0)
提交回复
热议问题