[英]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.