How to pass arguments to addEventListener listener function?

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

    The following answer is correct but the below code is not working in IE8 if suppose you compressed the js file using yuicompressor. (In fact,still most of the US peoples using IE8)

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

    So, we can fix the above issue as follows and it works fine in all browsers

    var someVar, eventListnerFunc;
    someVar = some_other_function();
    eventListnerFunc = some_function(someVar);
    someObj.addEventListener("click", eventListnerFunc, false);
    

    Hope, it would be useful for some one who is compressing the js file in production environment.

    Good Luck!!

提交回复
热议问题