我正在向函数返回一个方向字符串,我希望用返回值中的字符串替换jquery animate的left
属性。
我尝试了以下无效的
// my attempt at using string returned for property
function direction (data) {
// move the object in the direction given by x
$( "#cube" ).animate({
data.direction: "+=5" // here changed from left -> data.direction which has the direction string inside [left up right down]
}, 10, function() {
// Animation complete.
});
}
// original working example
function direction (data) {
// move the object in the direction given by x
$( "#cube" ).animate({
left: "+=5"
}, 10, function() {
// Animation complete.
});
}
答案 0 :(得分:1)
尝试创建属性设置为data.direction
的对象,将值设置为"+=5"
function direction (data) {
var opts = {}; opts[data.direction] = "+=5";
// move the object in the direction given by x
$( "#cube" ).animate(opts, 10, function() {
// Animation complete.
});
}
可选地,
var data = {
left:{left:""},
right:{right:"+=5"},
up:{up:""},
down:{down:""}
}
function direction (data) {
// move the object in the direction given by x
$( "#cube" ).animate(right, 10, function() {
// Animation complete.
});
}
direction(data.right)