How to generate event handlers with loop in Javascript? -
this question has answer here:
for example, have 10 tags generated ajax response:
<a href="#" id="b1">b1</a> <a href="#" id="b2">b2</a> <a href="#" id="b3">b3</a> <a href="#" id="b4">b4</a> <a href="#" id="b5">b5</a> <a href="#" id="b6">b6</a> <a href="#" id="b7">b7</a> <a href="#" id="b8">b8</a> <a href="#" id="b9">b9</a> <a href="#" id="b10">b10</a>
i need assign onclick event each of them via loop:
for(i=1; i<11; i++) { document.getelementbyid("b"+i).onclick=function() { alert(i); } }
this doesn't work, assigns onclick last tag , alerts "11". how can work? i'd prefer not use jquery.
all of handlers sharing same i
variable.
you need put each handler separate function takes i
parameter each 1 gets own variable:
function handleelement(i) { document.getelementbyid("b"+i).onclick=function() { alert(i); }; } for(i=1; i<11; i++) handleelement(i);
Comments
Post a Comment