传递对象属性

Passing object property

本文关键字:属性 对象      更新时间:2023-09-26

在我的小JS框架上工作。尝试创建切换方法。这是代码:

function $elect(id) {
    if (!(this instanceof $elect)) {
        return new $elect(id);
    }
    this.elm = document.getElementById(id);
}
$elect.prototype = {
    toggle:     function (prop, val1, val2) {
                    if (this.elm.style.prop != val2) {
                        this.elm.style.prop = val2;
                    } else {
                        this.elm.style.prop = val1;
                    }
                }
}
window.$elect = $elect;

并用$elect(id).toggle('background', 'red', 'blue')来称呼它。但这当然行不通。我正在想办法嗯...怎么说呢?我想将'background'传递给this.elm.style.prop,以便我也可以使用其他 css 属性。如何将this.elm.style.prop中的prop替换为我传递的参数?

您可以使用

object[key]

其中键是一个字符串。

所以在你的情况下,它会是

this.elm.style[prop]


http://jsfiddle.net/ZJWdA/下面是一个示例。