jquery单独包装list元素的每四个子元素

时间:2013-02-08 12:47:28

标签: jquery html

我在列表元素中对元素进行分组时遇到了麻烦。

对于例子,我有三个列表元素:

<ul class="row">
<li class="item"> 
<!-- product name -->
<div class="imglist"> 
<a href="#" title="image"><span class="txt">txt</span></a> 
</div>
</li>
</ul>

<ul class="row">
  <li class="item"> 
    <!-- product name -->
    <div class="imglist"> 
<a href="#" title="image"><span class="txt">txt</span></a> 
<a href="#" title="image"><span class="txt">txt</span></a> 
<a href="#" title="image"><span class="txt">txt</span></a>
<a href="#" title="image"><span class="txt">txt</span></a> 
<a href="#" title="image"><span class="txt">txt</span></a> 
<a href="#" title="image"><span class="txt">txt</span></a> 
</div>
</li>
</ul>

<ul class="row">
<li class="item"> 
<!-- product name -->
<div class="imglist"> 
<a href="#" title="image"><span class="txt">txt</span></a> 
<a href="#" title="image"><span class="txt">txt</span></a> 
</div>
</li>
</ul>

在Jquery我试过这个:

var divs = $("div.imglist > a");
for(var i = 0; i < divs.length; i+=4) {
divs.slice(i, i+4).wrapAll("<div class='group'></div>");
}

但现在的结果是:

<ul class="row">
<li class="item"> 
<!-- product name -->
<div class="imglist"> 
<div class="group">
<a href="#" title="image"><span class="txt">txt</span></a>
<a href="#" title="image"><span class="txt">txt</span></a>
<a href="#" title="image"><span class="txt">txt</span></a>
<a href="#" title="image"><span class="txt">txt</span></a></div> 
</div>
</li>

<li class="item"> 
<!-- product name -->
<div class="imglist">
<div class="group">
<a href="#" title="image"><span class="txt">txt</span></a>
<a href="#" title="image"><span class="txt">txt</span></a>
<a href="#" title="image"><span class="txt">txt</span></a>
<a href="#" title="image"><span class="txt">txt</span></a></div> 
</div>
</li>

<li class="item"> 
<!-- product name -->
<div class="imglist">   
<div class="group">
<a href="#" title="image"><span class="txt">txt</span></a></div> 
</div>
</li>
</ul>

我的问题是我想要单独包装每个li.item

2 个答案:

答案 0 :(得分:2)

分别浏览每个列表:

$('.imglist').each(function(){
    var divs = $('a', this);
    console.log(divs)
    console.log(divs.slice(0,4));
    for(var i = 0; i < divs.length; i+=4) {
        console.log(i)
        divs.slice(i, i+4).wrapAll('<div class="wrapper"></div>');
    }
});

演示:Fiddle

答案 1 :(得分:1)

如果我理解正确,您需要为每个li.item分组:

$("ul li.item").each(function() {
    $(this).find("a").wrapall("<div class='group'></div>");
});