我有4个div,我必须根据这个对象数组为每个对象应用背景,例如1 div是绿色,金色和2个div是红色。由于tix_pax为零,布朗不应该在那里。我知道方法css()但不知道循环逻辑是如何工作的。
[
{
"tix_type": "adult",
"bg": "gold",
"tix_pax": 1
},
{
"tix_type": "child",
"bg": "brown",
"tix_pax": 0
},
{
"tix_type": "senior",
"bg": "red",
"tix_pax": 2
},
{
"tix_type": "disabled",
"bg": "green",
"tix_pax": 1
}
]
答案 0 :(得分:0)
我认为你可以使用Sass完成类似的事情。从“@for”部分开始查看此处:http://thesassway.com/intermediate/if-for-each-while
答案 1 :(得分:0)
如果你为这个对象数组添加一个id属性,它将很容易循环,分别选择每个div并应用相应的颜色。
var objs = [
{
"id": "div1",
"tix_type": "adult",
"bg": "gold",
"tix_pax": 1
},
{
"id": "div2",
"tix_type": "child",
"bg": "brown",
"tix_pax": 0
},
{
"id": "div3",
"tix_type": "senior",
"bg": "red",
"tix_pax": 2
},
{
"id": "div4",
"tix_type": "disabled",
"bg": "green",
"tix_pax": 1
}
]
objs.forEach(function(ob) {
var div = document.selectElementById(obj.id)
div.style.backgroundColor = obj.bg
})
答案 2 :(得分:0)
你可以使用像
这样的循环
var array = [{
"tix_type": "adult",
"bg": "gold",
"tix_pax": 2
}, {
"tix_type": "child",
"bg": "brown",
"tix_pax": 0
}, {
"tix_type": "senior",
"bg": "red",
"tix_pax": 6
}, {
"tix_type": "disabled",
"bg": "green",
"tix_pax": 2
}];
var pos = 0,
$targets = $('.target');
array.forEach(function(obj, idx) {
snippet.log('color elements between '+pos +' and ' + (pos+obj.tix_pax)+' as '+obj.bg)
$targets.slice(pos, pos + obj.tix_pax).css('background-color', obj.bg);
pos += obj.tix_pax;
});

.target {
margin-bottom: 5px;
min-height: 10px;
border: 1px solid grey;
}

<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="target"></div>
<div class="target"></div>
<div class="target"></div>
<div class="target"></div>
<div class="target"></div>
<div class="target"></div>
<div class="target"></div>
<div class="target"></div>
<div class="target"></div>
<div class="target"></div>
&#13;
答案 3 :(得分:0)
真的不确定您希望div显示在哪里或者您希望它们放在页面中的位置。您的数据是有效的JSON,所以我只是解析它。我做了一个div#容器&#39;并且下面的代码将循环遍历您的数据,并根据tix_pax将正确数量的div与您想要的背景颜色添加到&#39;#container&#39; div如果tix_pax大于零
<!DOCTYPE html>
<html lang="en">
<head>
<title>Loopy</title>
<style>
.tix{
width:100px;
height:50px;
margin-right:10px;
float:left;
}
</style>
</head>
<body>
<div id="container"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
var data = '[{"tix_type": "adult","bg": "gold","tix_pax": 1},{"tix_type": "child", "bg": "brown", "tix_pax": 0 },{"tix_type": "senior", "bg": "red", "tix_pax":2}, {"tix_type": "disabled","bg": "green","tix_pax": 1}]';
var $data = JSON.parse(data);
$.each($data, function(i, v){
if(v.tix_pax>0){
for (var i = 0; i < v.tix_pax; i++) {
$('#container').append('<div class="tix" style="background-color:' + v.bg + ';"></div>');
}
}
});
</script>
</body>
</html>