2

我无法在列表元素中对元素进行分组。

例如,我有三个列表元素:

<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单独的包装。

4

2 回答 2

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>');
    }
});

演示:小提琴

于 2013-02-08T13:17:59.603 回答
1

如果我理解正确,您希望对每个 li.item 进行分组:

$("ul li.item").each(function() {
    $(this).find("a").wrapall("<div class='group'></div>");
});
于 2013-02-08T13:05:51.893 回答