2015-11-25 3 views
0

Я возвращаю строку направления для функции, и я хочу заменить свойство left для jquery animate со строкой в ​​возвращаемом значении.Использование строки данных как свойства в jquery animate

я попытался следующие, не работал

// 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. 
     }); 
    } 

ответ

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) 
Смежные вопросы