call addEventListener in loop with variable

前端 未结 1 1970
北恋
北恋 2021-01-17 06:04

I am new to JavaScript. I have a 6 elements that I want to equip with very similar event listeners. I have a working brute force solution that I want to improve, but (I thin

相关标签:
1条回答
  • 2021-01-17 06:31

    You need to put event listener mechanism inside closure, in laymen closure return value from inner function, you want your event listener should be present even after loop is executed or scope is finished.

    You need to wrap whole event or getElementByid inside closure, here is code snippet

      for (var id = 1; id <= 2; id++) {
         (function(id){
           elem = document.getElementById("court" + id + "button");
           elem.addEventListener(
            "click",
            function(event){wassern(id, event);},
            false
          );
          elem = document.getElementById("court" + id + "xbutton");
          elem.addEventListener(
            "click",
            function(event){abbrechen(id, event);},
            false
          );
        })(id)
      }
    

    for getting event you can pass this, this refer to event inside addEventListner

    Here is jsFiddle code http://jsfiddle.net/Xtgr4/

    Hope above answer make sense to you

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