javascript Jquery for 循环在每三次循环迭代后写入 html

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13144927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:56:12  来源:igfitidea点击:

Jquery for loop write html after every third iteration of loop

javascriptjqueryhtmlloops

提问by klye_g

I am trying to get a <div class="clear"></div>to appear after every third iteration of a for loop in jquery. I know in PHP it can be accomplished via if($i%3 == 0)but how does one do it in jquery/javascript?

我试图<div class="clear"></div>在 jquery 中的 for 循环每三次迭代后出现一个。我知道在 PHP 中它可以通过if($i%3 == 0)但如何在 jquery/javascript 中完成?

Here is my for loop:

这是我的 for 循环:

var data = $.parseJSON(result);
for(i=0;i<data.length;i++){
    if(i/3 == 1){
        $('#add_product_preview_area').append('<div class="clear"></div>');
    }
    $('#add_product_preview_area').append(data[i]);
}

Now this only works once since the loop will only get to the number 3 once. So any thoughts on how to make the same php concept work in jquery? I have seen the other questions about wrapping every nth in a div, but I just need to write the html of a div after each one.

现在这只有效一次,因为循环只会到达数字 3 一次。那么关于如何在 jquery 中使用相同的 php 概念有什么想法吗?我已经看到了关于在 div 中每 n 个包装的其他问题,但我只需要在每个 div 之后写一个 div 的 html。

Thanks in advance.

提前致谢。

EDIT:

编辑:

if ( i && (i % 3 === 0)) {

Is the answer..I didn't know you could do that. Thanks!

答案是......我不知道你能做到这一点。谢谢!

回答by I Hate Lazy

Use the modulus operator instead.

请改用模数运算符。

if ( i && (i % 3 === 0)) { ...

Whenever there's no remainder, you're evenly divisible by 3.

只要没有余数,您就可以被 整除3

I included the i &&to eliminate the first iteration since 0 % 3 === 0; // true.

我包括i &&以消除自 以来的第一次迭代0 % 3 === 0; // true

回答by Justin Self

Use this... just like your PHP

使用这个...就像你的 PHP

if (i % 3 == 0 )