将css属性添加到对象的集合中

Add css properties to a collection from an object

本文关键字:集合 对象 css 属性 添加      更新时间:2023-09-26

我需要使用jQuery在集合的每个元素上添加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);
})

这里不需要使用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根本无关——它是一个对象——因此我更改了它的名称。

您可以使用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>