循环结果数组的最后一个索引 [英] Looping result last index of array

查看:83
本文介绍了循环结果数组的最后一个索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,使用添加每个元素一个事件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);
        });
    })();
}

但是当我点击任何元素在循环中添加了一个事件,它总是显示最后一个索引 example 。比如当我点击元素时,它会在警告框内显示带有示例文本的警报。

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.

这是 elm = elm后 console.log(elm)的结果。 normalize()

here was the result of console.log(elm) after elm = elm.normalize()


[sample:input.sample.fld,example:input.example.fld]

[sample: input.sample.fld, example: input.example.fld]

isobj(elm)是一个函数检查变量是否为对象,与 iselm(elm)相同)函数,用于检查变量是否为元素

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.

由于修复此问题,我正在尝试使用,(function(){/ *我把如上所述的addEventListener * /})(); 在循环内部,但仍无效。

due to fix this, i'm trying to use, (function() { /* i put the addEventListener as above */ })(); inside the loop, but still not work.

我已确保 x 总是显示索引,但我不知道为什么它总是显示事件中的最后一个索引。

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.

推荐答案

到执行代码行时,for循环已经完成。

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

对于exp lanation: https://dzone.com/articles/为什么-javascript-loop-only-use-last-value

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

}

这篇关于循环结果数组的最后一个索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆