jquery 添加或切片
我正在尝试将一定数量的元素包装在 div
中。问题在于元素的数量可能会根据用户的输入而变化。因此元素的数量可以是 2、3、4 甚至更多。我有一个变量告诉我应该包装多少个元素。因此,例如,我的页面可能有这样的内容:
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
现在我需要根据我的变量将它们包装在另一个 div
中。所以,如果我的变量的值为 3,它看起来像这样:
<div class="testing">
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
</div>
<div class="testing">
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
</div>
我正在使用这段代码:
$(this).add($(this).next())
.add($(this).next().next())
.wrapAll('<div class="testing"></div>');
问题是我需要知道那里有多少个元素。有没有一种动态的方法来做到这一点?我还看到了 slice
函数并尝试像这样使用它:
for(var i=0;i<img_cnt;i+=img_row){
obj.children().slice(i,i+img_row).wrapAll('<div class="row"></div>');
}
但是它不起作用。我有 8 个 div。它应该将 3 个包裹在一起,所以我应该有 3 个新的 div
,前 2 个中有 3 个,最后一个有 2 个,因为只有 8 个 div
。但是,我在第一个新的 div
中得到了 3 个 div
,然后接下来的 2 个 div
根本没有换行,然后是最后一个3 个 div
包含在一个新的 div
中。我不知道为什么它没有正确包裹它。您对如何做到这一点或者甚至更好的方法有什么想法吗?
I am trying to wrap a certain number of elements in a div
. The problem is that the number of elements can vary based on the user's input. So the number of elements could be 2, 3, 4, or even more. I have a variable that tells me how many elements should be wrapped. So, for instance, my page may have this:
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
Now I need to wrap those in another div
based on my variable. So, if my variable held a value of 3, it would look like this:
<div class="testing">
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
</div>
<div class="testing">
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
</div>
I was using this code:
$(this).add($(this).next())
.add($(this).next().next())
.wrapAll('<div class="testing"></div>');
The problem with that is that I would need to know how many elements are going to be there. Is there a dynamic way to do this? I also saw the slice
function and tried to use it like this:
for(var i=0;i<img_cnt;i+=img_row){
obj.children().slice(i,i+img_row).wrapAll('<div class="row"></div>');
}
It is not working, though. I have 8 div
s. It should be wrapping 3 together, so I should have 3 new div
s with 3 in the first 2 and 2 in the last, since there are only 8 div
s. However, I get 3 div
s in the first new div
, then the next 2 div
s are not wrapped at all, and then the last 3 div
s are wrapped in a new div
. I am not sure why it is not wrapping it right. Do you have any ideas on how to do this or maybe even a better method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码无法正常工作,因为
children
正在发生变化。尝试在常量集上使用slice
:示例:http://jsbin.com/upaji
Your code isn't working because
children
is changing. Try usingslice
on a constant set:Example: http://jsbin.com/upaji