Javascript Dynamic Function Invocation
I want to do something kind of Rubyish in Javascript. I'm writing a wrapper around setting DOM element styles. That would go something like (on a per style basis):
ele.style.backgroundColor = someSetting
ele.style.padding = anotherSetting
What I'd like to do (and I'll use Ruby sy开发者_如何学编程ntax to illustrate) is:
class Element
def initialize(ele)
@ele = ele
end
def setDOMElementStyle(styleSettings = {})
styleSettings.each_pair do |styleAttribute, setting|
@element.style.send(styleAttribute, setting)
end
# Other wrapper stuff for elements here
end
element = Element.new document.createElement("div")
element.setDOMElementStyle :width => '60px', :height => '2px', :top => '0px', :left => '0px'
In Javascript, I can do this with the dreaded eval
, but I wondered if there was a neater way to handle it. Here's a hack at it with the evil eval
.
var Element, element;
Element = function() {
function Element(element) {
this.element = element;
}
Element.prototype.setDOMElementStyle = function(styleSettings) {
var setting, styleAttribute;
if (styleSettings == null) {
styleSettings = {};
}
for (setting in styleSettings) {
styleAttribute = styleSettings[setting];
eval("@element.style." + styleAttribute + " = " + setting);
}
}
}
element = new Element(document.createElement("div"));
element.setDOMElementStyle({
width: '60px',
height: '2px',
top: '0px',
left: '0px'
});
Thanks!
Use square braces:
element.style[styleAttribute] = setting
In JavaScript, every property can also be referred through square braces. Examples:
window.location.href === window["location"].href === window["location"]["href"]
=== window.location["href"]
精彩评论