我使用bulma和javascript创建一个新的div(具有类名列的div),并在每4个计数后添加4个具有类名“ column”的div。我在将4个div放在一个div下时遇到问题
let locations = [{name: 'location1',value: 11},{name: 'location2',value: 21},
{name: 'location3',value: 31},{name: 'location4',value: 41},
{name: 'location5', value: 51},{name: 'location6',value: 61},
{name: 'location7',value: 71},{name: 'location8',value: 71},
{name: 'location9',value: 71},
];
for (let i = 0; i < locations.length; i++) {
if (i == 0 || i % 3 == 0) {
$('#map-card').append(`<div class="columns"></div>`);
$('#map-card .columns').append(`<div class="column">${i}th Column created</div>`)
}
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="map-card"></div>
我想您需要的是将一行代码向下移动一点。
for (let i = 0; i < locations.length; i++) {
if (i == 0 || i % 3 == 0) {
$('#map-card').append(`<div class="columns"></div>`);
}
$('#map-card .columns:last').append(`<div class="column">${i}th Column created</div>`)
}
还请注意,我已经将:last
添加到$('#map-card .columns:last')
,所以我们总是将内容附加到新创建的.columns
Demo
let locations = [{
name: 'location1',
value: 11
}, {
name: 'location2',
value: 21
},
{
name: 'location3',
value: 31
}, {
name: 'location4',
value: 41
},
{
name: 'location5',
value: 51
}, {
name: 'location6',
value: 61
},
{
name: 'location7',
value: 71
}, {
name: 'location8',
value: 71
},
{
name: 'location9',
value: 71
},
];
for (let i = 0; i < locations.length; i++) {
if (i == 0 || i % 3 == 0) {
$('#map-card').append(`<div class="columns"></div>`);
}
$('#map-card .columns:last').append(`<div class="column">${i}th Column created</div>`)
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="map-card"></div>
let locations = [{ name: 'location1', value: 11 }, { name: 'location2', value: 21 }, { name: 'location3', value: 31 }, { name: 'location4', value: 41 }, { name: 'location5', value: 51 }, { name: 'location6', value: 61 }, { name: 'location7', value: 71 }, { name: 'location8', value: 71 }, { name: 'location9', value: 71 }];
let str = "",
n = 3;
for (let i = 0; i < locations.length; i++) {
str += (i % n == 0 ? `<div class="columns">` : '') +
`<div class="column">Column ${i} created</div>` +
(i % n == n - 1 ? `</div>` : '');
}
$('#map-card').html(str);
<link href="https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="map-card"></div>