Adding multi addEventListener to specific function
I want to do multi AddEventListener
to specific function, but the result is not what I want.
I get always the last child on the list.
Why?
This is the code:
First section:
<script>
var inside_elm= new Array();
inside_elm[1]="inside_e1";
inside_elm[2]="inside_e2";
inside_elm[3]="inside_e3";
var kk = {
showBox :function(elm){
alert(elm);
document.getElementById(elm).style.display='block';
}
}
function load() {
var e_elm= new Array();
e_elm[1]="e1";
e_elm[2]="e2";
e_elm[3]="e3";
for(var i=1;i<3;i++){
var k=e_elm[i];
alert(inside_elm[i]);
document.getElementById(e_elm[i]).addEventListener('click',function(){kk.showBox(inside_elm[i])},false);
}
}
</script>
The body:
<body onload="load();">
<div id="e1">
e1
<div id="inside_e1" style="display:none;">inside_e1</div>
</div>
<div id="e2">
e2
<div id="inside_e2" style="display:none;">inside_e2</div>
</div>
<div id="e3">
e3
<div id="inside_e3" style="display:none;">inside_e3</div>
</div>
It's basically down to the fact that it doesn't evaluate 'i' until the function executes, by which stage it's set to 3.
What you want to do is use something like the following:
for(var i=1;i<4;i++){
var k=e_elm[i];
alert(inside_elm[i]);
var elm = document.getElementById(e_elm[i]);
elm.inside_elm = inside_elm[i];
elm.addEventListener('click', function(){kk.showBox(this.inside_elm)},false);
}
I think it is down to the following, or at least it won't help matters.
for(i = 1;i < 3;i++){
....
}
Will only access the first two atoms of your array and will exit the loop before iterating the third time. Try
for(i = 1;i < 4;i++){
....
}
Similarly it is good practice to start array indices at 0 in which case
for(i = 0;i<3;i++){
....
}
would iterate through each (assuming the start index is 0)