[英]How to get variable into chained function with mootools
我创建了一个函数来为我的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
给该实例,因此,你可以做:
window['cfx' + i].start({'color': '#000000'}).chain(function(){
this.start({'color': color});
});
就是这样。 玩得开心
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.