问题描述
我试图在jquery的for循环的每次第三次迭代后出现< div class =clear>< / div>
。我知道在PHP中可以通过 if($ i%3 == 0)
来完成,但是如何在jquery / javascript中做到这一点?
这是我的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]);
$ b现在只能使用一次,因为循环只能达到3次。那么关于如何使相同的PHP概念在jQuery中工作的任何想法?我已经看到关于在div中包含每一个nth的其他问题,但我只需要在每个div后面写一个div的html。
在此先感谢。
编辑:
if(i&&(i %3 === 0)){
是答案..我不知道你可以去做。谢谢!
解决方案使用模数运算符。
if(i&&(i%3 === 0)){...
每当没有余数时,您可以被
3
均匀整除。
i&&
消除自0%3 === 0之后的第一次迭代; // true
。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 viaif($i%3 == 0)
but how does one do it in jquery/javascript?Here is my for loop:
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.
Thanks in advance.
EDIT:
if ( i && (i % 3 === 0)) {
Is the answer..I didn't know you could do that. Thanks!
解决方案Use the modulus operator instead.
if ( i && (i % 3 === 0)) { ...
Whenever there's no remainder, you're evenly divisible by
3
.I included the
i &&
to eliminate the first iteration since0 % 3 === 0; // true
.这篇关于循环每循环第三次循环后,jquery for循环写入html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!