How to pass arguments to addEventListener listener function?

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

    I was stuck in this as I was using it in a loop for finding elements and adding listner to it. If you're using it in a loop, then this will work perfectly

    for (var i = 0; i < states_array.length; i++) {
         var link = document.getElementById('apply_'+states_array[i].state_id);
         link.my_id = i;
         link.addEventListener('click', function(e) {   
            alert(e.target.my_id);        
            some_function(states_array[e.target.my_id].css_url);
         });
    }
    

提交回复
热议问题