我已经尝试了一些方法来获得这个工作,但我似乎错过了一些东西。
我有一个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>
我需要将每四个.staff-item
div包装到另一个div .staff-row
然而,我也需要记住,因为项目的数量可能不能被4整除,我可能需要提前结束一行(只有1,2或3 .staff-item
的内部)
所以我知道我可以使用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行。怎样才能得到这一行中的每四个元素呢?
我今天遇到了类似的问题。我相信有更优雅的方法来解决这个问题,但这是我最初的解决方案。
<?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;
}
}