Break loop for every 5th loop
I'd like to add a simple bit of code to my HTML (the list item) for every 5th loop.
Here is my code:
if (jsonData != null && jsonData.length > 0){
for (i=0;i<jsonData.length;i++){
if( jsonData[i].name.length > 15 )
cname = jsonData[i].name.substr(0,15);
else cname = jsonData[i].name ;
resHTML += '<li><a title="'+ jsonData[i].name +'" href="'+ jsonData[i].link开发者_开发知识库 +'"><img width="137" height="175" alt="'+ jsonData[i].name +'" src="'+ jsonData[i].img +'"></a><br><a href="'+ jsonData[i].link +'">'+ cname +'</a></li>' ;
}
}
So for every 5th loop, the <li>
would become <li style="margin-right:0">
Can anyone show me how to do this?
Thank you
if ((i % 5) == 0)
// add your margin stuff
Basically, the modulus (the remainder of i divided by 5) will be 0 every 5 iteration
You don't need to handle this with JavaScript.
Use this simple CSS:
li + li {
margin-left: 20px;
}
That will apply margin-left
to all except the first li
, which should be the same as applying margin-right
to all but the last li
.
+
is the adjacent sibling selector.
one possibility would be to test if i % 5 == 0
this will evaluate to true every 5 iterations of the loop.
code:
for(i = 0; i < n; i++)
{
if(!(i % 5))
{
//every fifth iteration!
}
}
I would.. set for(i = 1; i <= jsonData.length; i++)
Then do:
if((i % 5) == 0) { // margin code }
if((i%5)==0)
resHTML += "<li style=\"margin-right:0\">"
else
restHTML += "<li>"
restHTML += "<add all other stuff after li >"
精彩评论