简体   繁体   English

如何在for循环中每3次添加一个换行符

[英]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? 在一个天气小部件中,我有一个用于小时预报的for循环,但我需要将其分成4行,每行3条,而不是一行包含12个项目的行,我如何每3次添加一个换行符? Here is my for loop: 这是我的for循环:

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: 这是我的Hicon CSS,其他3个元素的CSS基本相同:

#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. 这是Hicon的HTML,其他项目在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] . i = [0,3,6,9]时,条件将达到4次。

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] . 您也可以根据@Tony Wu的建议使用(i%3==2) ,所以当i = [2,5,8,11]时,条件也将达到4倍。

Hope this helps. 希望这可以帮助。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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