2011-10-07 7 views
1

Javascript에서 Rubyish를하고 싶습니다. DOM 요소 스타일 설정에 대한 래퍼를 작성하고 있습니다. 즉 (스타일별로)과 같이 갈 것이다 :자바 동적 함수 호출

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

것은 내가하고 싶은 무엇 (내가 설명하기 위해 루비 구문을 사용합니다)입니다 :

자바 스크립트에서
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' 

, 두려워하는 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 

, 모든 속성은 또한 대괄호를 통해 참조 할 수 있습니다. 예 :

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

+1 30 초가 더 빠르다. –

+0

[웃긴 웃음] 나는 DOM 객체 중 일부가 정상 색인 가능 객체로 접근하는 것에 적대적 이었다는 것을 기억했다. 행복하게, 나는 틀렸어. 감사! –

관련 문제