Working on my little JS framework. Trying to create a toggle method. This is the code:
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;
And using $elect(id).toggle('background', 'red', 'blue')
to call it. But of course this won't work. I'm trying to find a way to hmm... how do I say it? I want to pass 'background'
to this.elm.style.prop
so I can also use the other css properties. How do I replace prop
in this.elm.style.prop
with the parameter I'm passing?
you can reference a key in an object with
object[key]
where key is a string.
So in your case, it'd be
this.elm.style[prop]
http://jsfiddle.net/ZJWdA/
Here's an example.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.