我需要在每5张图片后添加一个div标签,所以html标记应该是这样的:
<div>
<img src="http://farm1.static.flickr.com/143/321464099_a7cfcb95cf_t.jpg" />
<img src="http://farm4.static.flickr.com/3089/2796719087_c3ee89a730_t.jpg" />
<img src="http://farm1.static.flickr.com/79/244441862_08ec9b6b49_t.jpg" />
<img src="http://farm1.static.flickr.com/28/66523124_b468cf4978_t.jpg" />
</div>
<div>
<img src="http://farm1.static.flickr.com/163/399223609_db47d35b7c_t.jpg" />
<img src="http://farm1.static.flickr.com/135/321464104_c010dbf34c_t.jpg" />
<img src="http://farm1.static.flickr.com/40/117346184_9760f3aabc_t.jpg" />
<img src="http://farm1.static.flickr.com/153/399232237_6928a527c1_t.jpg" />
</div>
<div>
<img src="http://farm4.static.flickr.com/3629/3323896446_3b87a8bf75_t.jpg" />
<img src="http://farm4.static.flickr.com/3023/3323897466_e61624f6de_t.jpg" />
<img src="http://farm4.static.flickr.com/3650/3323058611_d35c894fab_t.jpg" />
<img src="http://farm4.static.flickr.com/3635/3323893254_3183671257_t.jpg" />
</div>
我必须使用foreach循环这个要求,除了我可以使用任何控制语句,任何人都可以提供任何这种逻辑的帮助,我尝试过这样的事情没有成功,最大的图像是100,那是为什么我将int初始化为100
foreach (var page in images)
{
int b = 100 ;
for (int a = 0 ; a = b ; a++)
{
<div><img src="page.name" alt="page.alt" /> </div>
}
}
答案 0 :(得分:1)
您可以计算行数,并在计数可被4整除时添加<div>
:
var count = 0;
foreach (var row in myData) {
// Open before rows 0, 4, 8, 12, 16, and so on
if (count%4 == 0) {
// Add <div>
}
// Write the line
// Close after rows 3, 7, 11, 15, and so on
if (count%4 == 3) {
// Add </div>
}
}
// Don't forget the closing row in case the number of images
// is not divisible by four
if (count%4 != 3) {
// Add </div>
}
答案 1 :(得分:1)
这些方面的东西应该让你朝着正确的方向前进
foreach (var page in images)
{
int b = 100 ;
bool first=true;
bool wroteDivEnd = false;
for (int a = 0 ; a = b ; a++)
{
wroteDivEnd=false;
if (a% 4==0)
{
if (!first)
{
// as long as this is not the first time we have written a
//start div, then we need to write and end one
//write previous div end </div>
wroteDivEnd=true;
}
//write new div start <div>
//set the flag so we know we have written the first start div
first=false;
}
// write out the images
<img src="page.name" alt="page.alt" />
}
//make sure your last </div> is written
if(!wroteDivEnd)
{
//write out the final missing </div>
}
}
答案 2 :(得分:1)
试试这个:
var imagesInDiv = 4;
var maxItems = 100;
for (var i = 0; i < images.Length && i < maxItems; ++i)
{
if (i % imagesInDiv == 0)
{
<div>
}
<img src="@images[i].name" alt="@images[i].alt" />
// if this is the last image in a set OR last image that you have OR last image allowed
if (i % imagesInDiv == imagesInDiv - 1 || i == images.Length - 1 || i == maxItems - 1)
{
</div>
}
}
编辑1:我添加了一些评论
答案 3 :(得分:0)
string finalstring = "";
foreach (var page in images)
{
for (int a = 0 ; a < 100 ; a++)
{
if (a % 4 != 0)
str += <img src="page.name" alt="page.alt" />;
else
{
str = "<div>" + str + "</div>";
finalstring += str;
str = "";
}
}
}