1

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Irvan Hilmi
  • 378
  • 1
  • 4
  • 16
  • 2
    You've *half*-applied one of the patterns that solves this problem, but only half of it. See the linked question's answers for details, but you need to pass `x` into your anonymous function inside the loop: `})(x);` rather than just `})();` (I use a different name for clarity, but many don't.) Separately: `for-in` is not how you loop through arrays; see [my answer here](https://stackoverflow.com/questions/9329446//9329476#9329476) for why and what to use instead (in this case, `forEach` would be particularly handy, as its callback would be the anonymous function). – T.J. Crowder Sep 11 '18 at 13:28
  • thanks a lot, it's a new knowledge for me. – Irvan Hilmi Sep 11 '18 at 13:34

1 Answers1

1

By the time that line of the code is executed, the for-loop has finished.

For explanation:https://dzone.com/articles/why-does-javascript-loop-only-use-last-value

You can use let if your browser supports it. (See article for explanation and alternatives)

var x, y, z;

elm = elm.normalize();
if(!isobj(elm) && iselm(elm)) {
    elm = new Array(elm);
}

for(x in elm) {
    (function() {
        let myX = x;
        elm[myX].addEventListener('click', function() {
            alert(myX);
        });
    })();

}
dustytrash
  • 1,568
  • 1
  • 10
  • 17