jQuery - 附加一个元素特定次数?
可以说,在这种情况下,我有 4 个名为“.CountThese”的 div,我只想这样做,获取该特定类的元素数量,然后附加一个 div 的次数与“.CountThese”的数量(在 this 情况下为 4 次)
这是 html:
<div class="CountThese"></div>
<div class="CountThese"></div>
<div class="CountThese"></div>
<div class="CountThese"></div>
<div class="appendHere"></div>
这将是结果:
<div class="CountThese"></div>
<div class="CountThese"></div>
<div class="CountThese"></div>
<div class="CountThese"></div>
<div class="appendHere">
<div class="appendedDIVs"></div>
<div class="appendedDIVs"></div>
<div class="appendedDIVs"></div>
<div class="appendedDIVs"></div>
</div>
到目前为止,我发现您可以计算这样的元素数量:
function divcount() {
var Count = $('.CountThese').length();
document.write(Count)
}
以为我不一定知道如何使用那..我真的不知道如何使用该数字来附加div或其他任何与此相关的东西..
如何实现这一点?
Lets say that in this case i have 4 divs called ".CountThese" and i wanted to do just that, get the number of elements with that specific class and then append a div as many times as was the amount of ".CountThese" ( 4 times in this case )
This is the html:
<div class="CountThese"></div>
<div class="CountThese"></div>
<div class="CountThese"></div>
<div class="CountThese"></div>
<div class="appendHere"></div>
This would be the result:
<div class="CountThese"></div>
<div class="CountThese"></div>
<div class="CountThese"></div>
<div class="CountThese"></div>
<div class="appendHere">
<div class="appendedDIVs"></div>
<div class="appendedDIVs"></div>
<div class="appendedDIVs"></div>
<div class="appendedDIVs"></div>
</div>
I got only so far that i found out that you can count number of elements something like this:
function divcount() {
var Count = $('.CountThese').length();
document.write(Count)
}
thought i dont necessarily know how to use that.. i seriously have no idea how i could then use that number to append divs or anything else for that matter..
How can this be achieved?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用数组 来避免手动迭代
join()
方法如下:其中 n 是要创建的元素数量。
这比接受的答案更好,因为它只操作 DOM 一次而不是
n
次。You can avoid the manual iteration by using the array
join()
method like:Where n is the number of elements you want to create.
This is better than the accepted answer since it only manipulates the DOM once rather than
n
times.您可以迭代 .CountThese div 并将每个 div 附加到 .appendHere
You can iterate over the .CountThese divs and for each one, append to .appendHere
最好的方法是迭代每个 .CountThese div,就像 Don 和 Christopher 提到的那样。不过,如果你想按照自己的方式来做,你可以这样做:
The best way to do it would be to iterate over each .CountThese divs like Don and Christopher mentioned. If you wanted to do it your way, though, you could do it like this: