Javascript 在循环中将动态参数传递给回调函数
我想动态设置一些jQuery动画 守则:Javascript 在循环中将动态参数传递给回调函数,javascript,jquery,function,callback,Javascript,Jquery,Function,Callback,我想动态设置一些jQuery动画 守则: function anim(data) { for (index in data) { (function(){ var props = {}; props[data[index].property] = data[index].value; data[index].elem.animate( props,
function anim(data) {
for (index in data) {
(function(){
var props = {};
props[data[index].property] = data[index].value;
data[index].elem.animate(
props,
500,
function() {
data[index].callback();
}
);
})();
}
}
var data =[
{
elem: elem1,
property: 'prop1',
value: 'val1',
callback: function() {
console.log('callback1');
}
},
{
elem: elem2,
property: 'prop2',
value: 'val2',
callback: function() {
console.log('callback2');
}
},
];
anim(data);
问题是绑定回调。启动回调时,数据[index]在当前范围内不可用。谁能告诉我如何设置这些回调属性吗?这里您使用了一个的闭包。您必须将数据[索引]作为参数传递
(function(dindex){
var props = {};
props[dindex.property] = dindex.value;
dindex.elem.animate(
props,
500,
function() {
dindex.callback();
}
);
})(data[index]);
这里你用了一个闭包。您必须将数据[索引]作为参数传递
(function(dindex){
var props = {};
props[dindex.property] = dindex.value;
dindex.elem.animate(
props,
500,
function() {
dindex.callback();
}
);
})(data[index]);
你也可以这样做
function anim(data) {
$.each(data, function(x,y){
var props = {};
props[y.property] =y.value;
y.elem.animate(
props,
500,
function() {
y.callback();
}
);
});
}
你也可以这样做
function anim(data) {
$.each(data, function(x,y){
var props = {};
props[y.property] =y.value;
y.elem.animate(
props,
500,
function() {
y.callback();
}
);
});
}
你将如何在数据中获得索引?为什么你需要生命的终结?你可以删除它以进行检查,也可以按照下面答案中的建议在那里传递索引。你将如何在数据中获取索引?为什么你需要关闭iLife?您可以删除它以进行检查,或者按照下面的答案中的建议传递索引+1.谢谢@Alexandru Ionutmihai方法+1.谢谢@亚历山德鲁·伊努特米海