2015-02-24 85 views
0

我在我的類中的下列方法:分配JSON作爲屬性

/** 
* Loops through a JSON object and assigns the styles to the element 
*/ 
this._assignClass = (function (className, element) { 
    for (var styleName in className) { 
     if (className.hasOwnProperty(styleName)) { 

      var style = element.style; 

      // *** THIS LINE IS NOT CORRECT *** 
      style.styleName = className[styleName]; 

     } 
    } 
}); 

及以下JSON對象:

this.configuration = { 
    class: { 
     arrowUp: { 
      width: "0px", 
      height: "0px", 
      borderLeft: "10px solid transparent", 
      borderRight: "10px solid transparent", 
      borderBottom: "10px solid black" 
     } 
    } 
}; 

我打電話,像這樣的方法:

this._assignClass(this.configuration.class.arrowUp, someDivElement); 

該方法應該採用JSON對象,並將所有樣式分配給來自對象的元素,在這種情況下爲this.configuration.class.arrowUp 。我遇到的問題是style.styleName被錯誤地解釋。我如何將正確的值傳遞給style

+0

'height:「0px」,'not'height:「0px」' - missing a comma – jdphenix 2015-02-24 04:27:36

+0

@jdphenix,我修正了那個錯誤。所述問題仍然存在。 – 2015-02-24 04:29:10

+1

當 - 你總是希望它是簡單的:) – jdphenix 2015-02-24 04:29:46

回答

3
this._assignClass = (function (className, element) { 
    for (var styleName in className) { 
     if (className.hasOwnProperty(styleName)) { 

      var style = element.style; 

      // *** TRY THIS ONE *** 
      style[styleName] = className[styleName]; 

     } 
    } 

});

+0

很好完成!謝謝。 – 2015-02-24 04:34:05

1

風格只是一個對象,所以你可以使用[]來分配它的屬性。

this._assignClass = (function (className, element) { 
    for (var styleName in className) { 
     if (className.hasOwnProperty(styleName)) { 
      //simply this would work 
      element.style[styleName] = className[styleName]; 
     } 
    } 
});