2011-10-07 79 views
1

我想在Javascript中做一些Rubyish。我正在編寫一個包裝設置DOM元素樣式。這將大大像(在每個風格的基礎上):Javascript動態函數調用

ele.style.backgroundColor = someSetting 
ele.style.padding = anotherSetting 

我今天準備這樣做(我會使用Ruby語法來說明)是:

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' 

在Javascript中,我可以用可怕的eval做到這一點,但我想知道是否有一個更好的方式來處理它。這是對邪惡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' 
}); 

謝謝!

+0

我不知道爲什麼你需要''eval',你可以使用jQuery和['.css()'](http://api.jquery.com/css/) ?或'.style [attr] = val'? –

+0

你已經使用'[]'來訪問'styleSettings [setting]'... – zzzzBov

+0

@DaveNewton用於教育目的的僞代碼。使用技巧不是學習語言的正確方法。 –

回答

8

使用方括號:

element.style[styleAttribute] = setting 

在JavaScript中,每個屬性也可以通過方括號提及。例如:

window.location.href === window["location"].href === window["location"]["href"] 
    === window.location["href"] 
+0

加快了30秒的+1 +1 –

+0

[尷尬的笑容]我記得一些DOM對象只是作爲普通的可索引對象訪問。令人高興的是,事實證明我錯了。謝謝! –