我尝试了一些方法来实现这个功能,但我似乎错过了一些东西。
我有一个for
循环,它遍历一个对象并通过将它附加到包装器#staff-list-wrapper
为每个对象输出一张图片。它目前在自己的.staff-item
div中输出35张图片。
for(var i=0;i<staffArray.length;i++){
var img = '<div class="staff-item"><img id="'+staffArray[i].slug+'" src="'+staffArray[i].pic_url+'" /></div>';
$('#staff-list-wrapper').append(img);
}
生成的HTML:
<div id="staff-list-wrapper">
<div class="staff-item">
<img id="felicity" src="http://localhost/something/wp-content/uploads/about_us_Felicity.jpg">
</div>
<div class="staff-item">
<img id="hannah" src="http://localhost/something/wp-content/uploads/about_us_Hannah.jpg">
</div>
</div>
我需要在另一个div .staff-item
.staff-row
div
但是我还需要记住,因为项目数量可能无法被4整除,我可能需要提前结束一行(只有1,2或3 .staff-item
&#39; s内侧)
所以我理解我可以使用modulo
运算符来检查/ 4计算的余数。
然而,我似乎无法在逻辑上正确输入内部这些行。我能够为每4个项目输出足够的行(在这种情况下为9行):
var rowCount = 1;
if(i % 4 === 0 ){
$('#staff-list-wrapper').append('<div class="staff-row" id="staff-row-'+rowCount+'" ></div>');
}
这会创建9行。如何获得该行中的每四个项目?
答案 0 :(得分:0)
我今天遇到了类似的问题。我相信有更优雅的方法可以解决这个问题,但这是我最初的解决方案。
<?php
$testArray = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
$numberOfElementsInArray = count($testArray);
$positionInArray = 0; // need to save our position
$howManyForFullSet = 4; // pick how many items you want in each set
$fullSets = floor($numberOfElementsInArray / $howManyForFullSet);
$remaining = $numberOfElementsInArray % $howManyForFullSet;
echo "number of elements in array = " . $numberOfElementsInArray;
echo "\n";
echo "full sets of (" . $howManyForFullSet . ") = " . $fullSets;
echo "\n";
echo "remaining elements = " . $remaining;
echo "\n";
echo "\n";
for ($i = $fullSets; $i > 0; $i--) { // loop for each full set
for ($j = $howManyForFullSet; $j > 0; $j--) { // each element in set
echo($testArray[$positionInArray]);
$positionInArray += 1;
}
echo "\n";
}
if ($remaining !== 0) {
for ($k = $remaining; $k > 0; $k--) { // if we have remainder items display them
echo($testArray[$positionInArray]);
$positionInArray += 1;
}
}