作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
让我们看一些伪 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/
我是一名优秀的程序员,十分优秀!