2016-05-09 50 views
2

我需要使用jQuery在集合的每个元素上添加CSS属性。有什么建议么?将css属性添加到来自对象的集合

var jsonCss = { 
    "color": "#555555", 
    "font-weight": "bold", 
    "text-align": "left" 
}; 

var $tdCollection = $("tr:first-child").find("td:nth-child(2)"); //A collection of <td> elements 
$.each($tdCollection, function(k, v){ 
    v.css(jsonCss); 
}) 
+0

使用类和类添加到您想给CSS – guradio

+0

谢谢你帮助的元素。我必须使用JSON对象。 – zm455

回答

4

你并不需要在这里使用each(),你可以应用CSS设置jQuery对象中的所有元素:

var cssObject = { 
    "color": "#555555", 
    "font-weight": "bold", 
    "text-align": "left" 
}; 

var $tdCollection = $("tr:first-child").find("td:nth-child(2)"); 
$tdCollecton.css(cssObject); 

另外请注意,对象定义其持有CSS规则与JSON完全无关 - 它是一个对象 - 因此我改变了它的名字。

2

您可以使用for...in

var jsonCss = { 
 
    "color": "#555555", 
 
    "font-weight": "bold", 
 
    "text-align": "left" 
 
}; 
 

 
var $tdCollection = $("tr:first-child").find("td:nth-child(2)"); 
 
for (var p in jsonCss) { 
 
    $tdCollection.css(p, jsonCss[p]); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table> 
 
    <tr><td>Lorem</td><td>Lorem</td></tr> 
 
</table>