我有一组通过WordPress Ajax填充的JSON数据。
["http://inovar.dev/wp-content/uploads/2016/11/FR991-Eco-Oak-A1.jpg",…]
此刻的项目总数为69.如何将其分组为每组18个项目。然后像这样包装:
<div class="slide">
<a class="floor-thumbnail"><img src="/wp-content/uploads/2017/01/BG_2-3.jpg" alt=""/></a>
<a class="floor-thumbnail"><img src="/wp-content/uploads/2017/01/BG_2-3.jpg" alt=""/></a>
<a class="floor-thumbnail"><img src="/wp-content/uploads/2017/01/BG_2-3.jpg" alt=""/></a>
<a class="floor-thumbnail"><img src="/wp-content/uploads/2017/01/BG_2-3.jpg" alt=""/></a>
<a class="floor-thumbnail"><img src="/wp-content/uploads/2017/01/BG_2-3.jpg" alt=""/></a>
<a class="floor-thumbnail"><img src="/wp-content/uploads/2017/01/BG_2-3.jpg" alt=""/></a>
答案 0 :(得分:1)
这样可以解决问题:
var arr = ["http://inovar.dev/wp-content/uploads/2016/11/FR991-Eco-Oak-A1.jpg",…];
var itemsPerBlock = 18;
var htmlStr = '<div class="slide">'
arr.forEach( function (d, idx) {
htmlStr += '<a class="floor-thumbnail"><img src="' +
d.split('inovar.dev')[1] +
'" alt=""/></a>';
if ((idx+1) % itemsPerBlock == 0 )
htmlStr += '</div><div class="slide">';
})
htmlStr += '</div>';
$('body').append(htmlStr); //append this to body
答案 1 :(得分:0)
var urls = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22];
var href = function (url) {
return '<a class="floor-thumbnail"><img src="' + url + '" alt=""/></a>\r\n'
}
var groupLimit = 18;
var output = urls.reduce(function (htmlString, current, index) {
var mod = index %groupLimit;
if (mod === 0) {
if (index >= groupLimit) htmlString += '</div>\r\n';
htmlString += '<div class="slide">\r\n'
}
return htmlString + href(current)
}, '') + '</div>';
console.log(output)
&#13;
答案 2 :(得分:0)
var arr = [
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19,
20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39
],
items = 18;
var parent = document.body // or parent
for ( var i=0; i < arr.length; i++ )
{
if ( i % items == 0 )
{
var el = document.createElement('div');
el.classList.add('slide');
parent.appendChild( el )
}
var a = document.createElement('a');
a.classList.add('floor-thumbnail');
el.appendChild( a );
var img = document.createElement('img');
img.src = arr[i];
a.appendChild( img )
}
&#13;