我想創建一個基於對象列表的顏色列表。我的問題是如何動態設置根據data.corporate.colour.hex
創建的每個li
的background-color
。我嘗試了一些沒有成功的事情。我怎樣才能做到這一點?如何將CSS屬性應用於使用JavaScript的動態生成HTML?
預先感謝您。
var data = {
corporate: [{
name: "blue",
colour: {
rgb: "RGB 0, 25, 168",
hex: "0019A8"
}
},
{
name: "red",
colour: {
rgb: "RGB 145, 25, 168",
hex: "00eeA8"
}
}
]
};
var output = [];
for (var i in data.corporate) {
output.push("<li>" +
data.corporate[i].name + " " +
data.corporate[i].colour.rgb + "--" +
data.corporate[i].colour.hex + "</li>");
}
console.log(output);
$("#placeholder").html(output);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="placeholder"></ul>
「style ='background-color:#」+ data.corporate [i] .hex +「' –
https://stackoverflow.com/questions/2173229/how-do-i-write-a-rgb-color -value-in-javascript – warl0ck
你可以添加類到它:https://stackoverflow.com/questions/507138/how-do-i-add-a-class-to-a-given-element – tech2017