How to pass arguments to addEventListener listener function?

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

    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.
     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

提交回复
热议问题