如何从json中检查true或false,如果为true或false则为div添加不同的css:
例如json:
{
"Object": [
{
"test": true,
"number": "001"
}, {
"test": false,
"number": "002"
}, {
"test": false,
"number": "003"
}, {
"test": true,
"number": "004"
}]
}
我创建了html:
<div class="test" id="001">001</div>
<div class="test" id="002">002</div>
<div class="test" id="003">003</div>
<div class="test" id="004">004</div>
我试过这样的事情,但这是错误的......
if (test == 'true') {
$(".test").css("background-color", "blue");
} else {
$(".test").css("background-color", "red");
}
答案 0 :(得分:1)
$.each(json.Object, function(index, value) {
$number = $("#"+value.number);
if(value.test) $number.css("background-color", "blue");
else $number.css("background-color", "red");
});
或
$.each(json.Object, function(index, value) {
$("#"+value.number).css("background-color", (value.test ? "blue" : "red"));
});
答案 1 :(得分:0)
如果我可以继续这个问题...我怎样才能在蓝色背景颜色的div上设置点击并禁用点击红色div?
$.each(json.Object, function (index, value) {
$("#" + value.number).css("background-color", (value.test ? "blue" : "red"));
$(".test").click(function (event) {
$("#" + value.number).css("background-color", (value.test ? "blue" : "red"));
$(this).css("background-color", "black");
});
});