循环结果数组的最后一个索引

编程入门 行业动态 更新时间:2024-10-28 19:21:52
本文介绍了循环结果数组的最后一个索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下代码,使用添加每个元素一个事件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: dzone/articles/为什么-javascript-loop-only-use-last-value

For explanation:dzone/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); }); })(); }

更多推荐

循环结果数组的最后一个索引

本文发布于:2023-10-28 18:55:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1537486.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   索引

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!