I have the following code, to add each element an event using addeventlistener
:
var x, y, z;
elm = elm.normalize();
if(!isobj(elm) && iselm(elm)) {
elm = new Array(elm);
}
for(x in elm) {
(function() {
elm[x].addEventListener('click', function() {
alert(x);
});
})();
}
but when I click any element
that added an event by the loop it always show the last index example
, like when I click the element
it show an alert with example
text inside the alert box.
Here was the result of console.log(elm)
after elm = elm.normalize()
:
[sample: input.sample.fld, example: input.example.fld]
isobj(elm)
is a function
to check if variable
is an object
, same like
iselm(elm)
is a function
to check if variable
is an element
.
Due to fix this, I'm trying to use, (function() { /* I put the addEventListener as above */ })();
inside the loop, but still not work.
I already make sure that x
is always showing it index, but I didn't know why it always showing the last index in the event.
Please help.