问题描述
让我们看一些伪Mootools代码:
Let's take some pseudo-Mootools code:
for loop (i) from 0 to 5 {
create.element {
id: 'element_'+i
}
$('element_'+i).addevent.click {
alert(i);
}
}
事件已正确添加到元素中.但是,当单击它们时,它们都会提醒最新的迭代器...应该是5.
The events get added to the elements properly. However, when clicked, they'll all alert the latest iterator... which would be 5.
是否可以通过某种方式更改"alert(i)"以在该时间点提醒迭代器?
Is there any way I can change "alert(i)" in the event to alert the iterator at that point in time?
.toString并没有做什么.
.toString didn't do much.
推荐答案
http://www .jsfiddle.net/dimitar/sbytJ/1/
for (var ii = 0; ii < 5; ++ii) {
new Element("div#id_" + ii + ".monkey[text=click me]").store("id", ii).addEvent("click", function() {
alert(this.retrieve("id") + " id: " + this.get("id"));
}).inject(document.body);
}
使用元素存储(element.store("id", ii)
/this.retrieve("id")
)是在运行时确保正确引用值的一种方法...
using the element storage (element.store("id", ii)
/ this.retrieve("id")
) is one way of ensuring correct value reference at runtime...
通过匿名函数的另一种方法: http://www.jsfiddle.net/dimitar/sbytJ/2/
another way via an anonymous function: http://www.jsfiddle.net/dimitar/sbytJ/2/
for (var ii = 0; ii < 5; ++ii) {
(function(id) {
new Element("div#id_" + id + ".monkey[text=click me]").addEvent("click", function() {
alert(id);
}).inject(document.body);
})(ii);
}
等.我敢肯定,还有其他方法可以重构它
etc etc. i am sure there are other ways to refactor this also
这篇关于呼应"then"即使var已更改,mootools事件中变量的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!