我创建了一个函数来为我的 html 表单增添趣味,该函数将检查提交时所有字段是否有效,如果无效,它们会闪烁红色以警告用户。在它尝试将颜色恢复正常之前,一切都很好。
if (response.length > 0) {
for (var i = 0; i < response.length; i++) {
if (response[i].getAttribute('field') != '') {
var errField = $(response[i].getAttribute('field')+'Err');
if (errField) {
errField.set('html', response[i].getAttribute('msg'));
var color = errField.getStyle('color');
window['cfx'+i] = new Fx.Morph(errField, {
duration: 400,
transition: Fx.Transitions.Quad.easeInOut
});
window['cfx'+i].start({'color': '#000000'}).chain(function() {
window['cfx'+i].start({'color': color});
});
}
}
}
}
我已经调试到可以判断它在进入链接函数内部时崩溃的地步,因为它在那个点丢失了变量。我环顾四周,但无法弄清楚如何让 i
进入链函数工作。
最佳答案
呃。基本上,迭代器将运行,传递给链接函数的 i
的值将始终是迭代中最后一项的索引。
您可以做几件事 - 调用附近的本地闭包是其中之一,或者重写整个循环以使用 Array.prototype.each
,如下所示:
response.each(function(el, i){
if (el.getAttribute('field') != ''){
var errField = $(el.getAttribute('field') + 'Err');
if (errField){
errField.set('html', el.getAttribute('msg'));
var color = errField.getStyle('color');
window['cfx' + i] = new Fx.Morph(errField, {
duration: 400,
transition: Fx.Transitions.Quad.easeInOut
});
window['cfx' + i].start({'color': '#000000'}).chain(function(){
window['cfx' + i].start({'color': color});
});
}
}
});
上面的i
的值会在每次迭代时固定到函数作用域内的迭代器中,从而产生预期的效果。
或者,这些将起作用:
// permanent reference
var cfx = window['cfx' + i];
cfx.start({'color': '#000000'}).chain(function(){
cfx.start({'color': color});
});
// binding the function via the outer scope to the element
window['cfx' + i].start({'color': '#000000'}).chain(function(){
this.start({'color': color});
}.bind(window['cfx' + i]));
// encapsulating the i into a local closure
(function(i){
// i is immutable here
window['cfx' + i].start({'color': '#000000'}).chain(function(){
window['cfx' + i].start({'color': color});
});
}(i));
最后,链式函数的范围是 Fx 实例,它保留对 this.element
中链式元素的引用,因此 this 将始终指向元素和 this
到实例,因此你可以这样做:
window['cfx' + i].start({'color': '#000000'}).chain(function(){
this.start({'color': color});
});
就是这样。玩得开心
关于javascript - 如何使用 mootools 将变量放入链式函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22912545/