javascript - Number value wrong in event bound through a for loop -
var rows = document.getelementsbyclassname('row'); (var = 0, l = rows.length; < l; i++) { if (i % 2 === 0) { $(rows[i]).click(function () { alert('i line number ' + i); } } } hi, how actual line number each row ? since when trigger click event on row, upper bound value alerted (i.e: rows.length = 7, i 6 each row clicked).
the problem upon click event triggered, i variable changed loop iteration. theoretically can use closure make things working, i.e.
for (var = 0, l = rows.length; < l; i++) { if (i % 2 === 0) { (function(i) { $(rows[i]).click(function() { alert("i line number " + i); }); )(i); } } practically, if use jquery (as understood code), easier use :even selector:
$(".row:even").click(function() { alert("i line number " + $(".row").index(this)); });
Comments
Post a Comment