简体   繁体   中英

How to add a line break every 3 times in a for loop

In a weather widget I have this for loop for an hourly forecast, but I need it split into 4 lines of 3 instead of a single line with 12 items, how do I add a line break every 3rd time? Here is my for loop:

for (var i = 0; i<12; i++) {
    document.getElementById("Hicon" + i).style.left = 1.4 +  8.333*i + "%";
    document.getElementById("Hpop" + i).style.left = 2.5 +  8.333*i + "%";
    document.getElementById("Hour" + i).style.left = 1.57 +  8.333*i + "%";
    document.getElementById("Htemp" + i).style.left = 1.3 +  8.333*i + "%";
}

Here is my css for Hicon, the css for the other 3 elements are much the same:

#Hicon0, #Hicon1, #Hicon2, #Hicon3, #Hicon4, #Hicon5, #Hicon6, #Hicon7, #Hicon8, #Hicon9, #Hicon10, #Hicon11 {
    position: absolute;
    top: 5%;
    left: 1.4%; /* set in main.js */
    width: 5.5%;
    height: 40%;
}

Here is HTML for the Hicon, other items are the same format inside the hourlyforecast div.

    <div id="hourlyforecastContainer" class="scaleZero">
        <div id="hourlyforecast">
            <div id="hourlyforecastBG"></div>
            <img id="Hicon0" src="Icon Sets/blank.png"/>
            <img id="Hicon1" src="Icon Sets/blank.png"/>
            <img id="Hicon2" src="Icon Sets/blank.png"/>
            <img id="Hicon3" src="Icon Sets/blank.png"/>
            <img id="Hicon4" src="Icon Sets/blank.png"/>
            <img id="Hicon5" src="Icon Sets/blank.png"/>
            <img id="Hicon6" src="Icon Sets/blank.png"/>
            <img id="Hicon7" src="Icon Sets/blank.png"/>
            <img id="Hicon8" src="Icon Sets/blank.png"/>
            <img id="Hicon9" src="Icon Sets/blank.png"/>
            <img id="Hicon10" src="Icon Sets/blank.png"/>
            <img id="Hicon11" src="Icon Sets/blank.png"/>

You can add condition using Remainder (%) :

if ( i%3 == 0 )
{
   //Break here
}

The condition will be achieved 4 times when i = [0,3,6,9] .

You can also use (i%3==2) based on @Tony Wu suggestion, so the condition will be achieved 4 times also but when i = [2,5,8,11] .

Hope this helps.

if(i % 3 == 0) {do your thing}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM