gpt4 book ai didi

javascript - 在循环中添加div jquery

转载 作者:行者123 更新时间:2023-12-02 14:24:50 25 4
gpt4 key购买 nike

所以当我选择像这样的一些div时

  var filter = $('.album1.phonepic');

我想将它们添加到我已有的空 div 中,但每个 div 只能添加 4 个。

   <div class="emptydiv1"></div>
<div class="emptydiv2"></div>
var count = 0;

for(var i = 0; i <= filter.length; i++){
if(count <= 4){
$('.emptydiv1').append(filter[i]);
count++;
}else {
$('.emptydiv2').append(filter[i]);
}
}

每当我尝试循环选定的变量时,它都不起作用。请帮助我

最佳答案

这里有一些适合您的简单代码

var filter = $('.album1.phonepic');

for (var i = 0; i <= filter.length; i++) {
var emptyDiv = i < 4?$('.emptydiv1'):$('.emptydiv2');
emptyDiv.append(filter[i]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="album1 phonepic">Test 1</span>
<span class="album1 phonepic">Test 2</span>
<span class="album1 phonepic">Test 3</span>
<span class="album1 phonepic">Test 4</span>
<span class="album1 phonepic">Test 5</span>
<span class="album1 phonepic">Test 6</span>
<span class="album1 phonepic">Test 7</span>
<span class="album1 phonepic">Test 8</span>

<hr/>
<div class="emptydiv1">div 1</div>
<hr/>
<div class="emptydiv2">div 2</div>

或使用 :lt():gt:() 的其他方式

var albums  = $('.album1.phonepic');


$('.emptydiv1').append(albums.filter(':lt(4)'))
$('.emptydiv2').append(albums.filter(':gt(3)'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="album1 phonepic">Test 1</span>
<span class="album1 phonepic">Test 2</span>
<span class="album1 phonepic">Test 3</span>
<span class="album1 phonepic">Test 4</span>
<span class="album1 phonepic">Test 5</span>
<span class="album1 phonepic">Test 6</span>
<span class="album1 phonepic">Test 7</span>
<span class="album1 phonepic">Test 8</span>

<hr/>
<div class="emptydiv1">div 1</div>
<hr/>
<div class="emptydiv2">div 2</div>

或数组切片方式

var _array = $('.album1.phonepic');

$('.emptydiv2').append(_array.slice(4))
$('.emptydiv1').append(_array.slice(0,4))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="album1 phonepic">Test 1</span>
<span class="album1 phonepic">Test 2</span>
<span class="album1 phonepic">Test 3</span>
<span class="album1 phonepic">Test 4</span>
<span class="album1 phonepic">Test 5</span>
<span class="album1 phonepic">Test 6</span>
<span class="album1 phonepic">Test 7</span>
<span class="album1 phonepic">Test 8</span>

<hr/>
<div class="emptydiv1">div 1</div>
<hr/>
<div class="emptydiv2">div 2</div>

关于javascript - 在循环中添加div jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38366453/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com