Event trigger issue using Javascript

时间:2015-10-29 15:54:29

标签: javascript html5

I'm writing a dynamic list and for some reason all my events are triggered using the same ID (all rows of the list can trigger the event, but using the same ID). My rows have different IDs but for some reason, the event is triggered with the latest entry on the list. Here is the code of the list:

<div class="listContainer" style="width: 100%; overflow-y: auto;">
<div id="card-list" class="container-fluid">
  <div class="row row-space" id="row1">
     <div class="row-basic" id="rowClass1" style="background-color: rgb(247, 245, 248);">
        <div class="circle"></div>
        <div class="testTitleContainerBar" style="color: rgb(79, 101, 114);">#1</div>
        <div class="totalNumberContainerBar" style="color: rgb(79, 101, 114);">5 Images</div>
        <div class="square"><img src="assets/Menu 2-24.png"></div>
        <div class="onePixelSeparatorBar"></div>
     </div>
     <div class="row-advanced" style="height: 0px; visibility: visible;">  </div>
  </div>
  <div class="row row-space" id="row2">
     <div class="row-basic" id="rowClass2">
        <div class="circle"></div>
        <div class="testTitleContainerBar">#2</div>
        <div class="totalNumberContainerBar">5 Images</div>
        <div class="square"><img src="assets/Menu 2-24.png"></div>
        <div class="onePixelSeparatorBar"></div>
     </div>
     <div class="row-advanced" style="height: 0px; visibility: visible;">  </div>
   </div>
</div>

The event listner is added dynamically like that:

 row = document.createElement('div');
 row.classList.add('row');
 row.classList.add('row-space');
 idNumber = total_Tests;
 row.id = "row"+idNumber;
 row.addEventListener('click', function() {openRow('#'+row.id)});

Can someone help me to understand what's going on?

1 个答案:

答案 0 :(得分:0)

You are reusing variable row inside a loop, and by the time click handler executes it references the last row. Capture the current id value:

row.addEventListener('click', (function(id) {
  return function() { openRow('#'+id); }
})(row.id));

or

row.addEventListener('click', function() {openRow('#'+this.id)});