我希望按类逐个堆叠div,所以如果div的类为" icon1"那么下面的div将是" icon2"。我想在每个循环中id。以防止多个Dom操作
var arr = [{
"id": 1,
"name": "foo"
}, {
"id": 1,
"name": "foo"
}, {
"id": 2,
"name": "foo"
}, {
"id": 1,
"name": "foo"
}];
var type = '';
var template ='';
$.each(arr, function() {
if (this['id'] == 1) {
type = 'icon1';
} else {
type = 'icon2';
}
template += '<div class="icon '+type+'">'+
'<p>ID: '+type+' Name: '+this['name']+'<p></div>';
});
$('#foo').html(template);
&#13;
.icon1 {
color: red;
}
.icon2 {
color: pink;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
</div>
&#13;
我正在寻找的结果将是:
icon1
icon2
icon1
icon2
icon1
icon2
etc...
答案 0 :(得分:1)
您可以使用css nth-child 属性来获取此样式
div:nth-child(odd) {
color: red;
}
div:nth-child(even) {
color: pink;
}
答案 1 :(得分:1)
这是一个解决方案:
var array = [
{
"id": 1,
"name": "foo"
},
{
"id": 1,
"name": "foo"
},
{
"id": 2,
"name": "foo"
},
{
"id": 1,
"name": "foo"
}
];
var lsts = [ [], [] ];
$.each( array, function() {
lsts[ this.id - 1 ].push( this );
} );
var lst1 = lsts[ 0 ],
lst2 = lsts[ 1 ];
for ( var i = 0, l = lst1.length, l2 = lst2.length; i < l || i < l2; i++ ) {
if ( i < l )
appendElement( lst1[ i ] );
if ( i < l2 )
appendElement( lst2[ i ] );
}
function appendElement( obj ) {
$( '#bar' ).append( '<div class="icon' + obj.id + '">' + obj.name + '</div>' );
}
.icon1 {
color: red;
}
.icon2 {
color: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="bar"><div>
小心其他身份证号码。