jQuery - attach event to dynamic element -


i have read through .on documentation, there bug in it

here html:

<a href="#" class="add-new">make new row</a>  <ul>     <li class="opts" >         <select class="change" href="#" data-row="1">             <option>a</option>             <option>b</option>             <option>c</option>         </select>     </li> </ul> 

here javascript:

 var index = 2;  $('.add-new').on('click',function(e) {       e.preventdefault();       $('.opts:first').clone(true).insertafter('.opts:last');      $('.opts:last select').attr("data-row", index);       index++;   });   $(document).on('click', '.change', function(e) {       e.preventdefault();       console.log($(this).data('row'));   }); 

if dynamically generate rows, new elements work .on event.
if first element changed , more new elements added, new new ones fire event.
act though first element.

here example: http://jsfiddle.net/bgasy/2/
add 1 or 2 rows , change first select.
console shows correct corresponding number when changed.
add few more rows , change new selects.
still fine, change first select, add more rows , change newest selects.
console shows 1, thinks newest rows first row.

what missing here?

change

$(this).data('row') 

to

$(this).attr('data-row') 

and seems solve issue.

fiddle


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -