gpt4 book ai didi

javascript - 即使在 var 发生更改后,仍会在 mootools 事件中回显变量的 "then"状态

转载 作者:行者123 更新时间:2023-12-02 20:31:25 24 4
gpt4 key购买 nike

让我们看一些伪 Mootools 代码:

for loop (i) from 0 to 5 {
create.element {
id: 'element_'+i
}
$('element_'+i).addevent.click {
alert(i);
}
}

事件已正确添加到元素中。然而,当点击时,它们都会提醒最新的迭代器......这将是 5。

有什么方法可以更改事件中的“alert(i)”以在该时间点提醒迭代器吗?

.toString 没有做太多事情。

最佳答案

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")) 是确保正确值引用的一种方法在运行时...

通过匿名函数的另一种方式: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);
}

等等,我确信还有其他方法可以重构它

关于javascript - 即使在 var 发生更改后,仍会在 mootools 事件中回显变量的 "then"状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4054915/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com