Javascript 传递对象属性
在我的小JS框架上工作。正在尝试创建切换方法。代码如下:Javascript 传递对象属性,javascript,css,parameters,frameworks,parameter-passing,Javascript,Css,Parameters,Frameworks,Parameter Passing,在我的小JS框架上工作。正在尝试创建切换方法。代码如下: function $elect(id) { if (!(this instanceof $elect)) { return new $elect(id); } this.elm = document.getElementById(id); } $elect.prototype = { toggle: function (prop, val1, val2) {
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]
其中key是一个字符串
所以在你的情况下,应该是
this.elm.style[prop]
这里有一个例子。Sweet。顺便说一句,你说的“密钥”是指它的属性吗?这是全新的。根据我的经验,它们是可以互换的术语。