我有以下代码,使用添加每个元素一个事件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); }); })(); }更多推荐
循环结果数组的最后一个索引
发布评论