Looping result last index of array [duplicate]

一笑奈何 提交于 2019-12-24 09:14:42

问题


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 didnt know why it always showing the last index in the event.

please help, thanks in advice.


回答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);
        });
    })();

}


来源:https://stackoverflow.com/questions/52276979/looping-result-last-index-of-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!