javascript-jQuery:将相似项目分组

使用jQuery,我试图将类似的项目分组到一个列表中.这就是我想要做的.给出如下列表:

<ul>
    <li class="foo">Item #1</li>
    <li class="foo">Item #2</li>
    <li class="foo">Item #3</li>
    <li class="bar">Item #4</li>
    <li class="bar">Item #5</li>
    <li class="foo">Item #6</li>
    <li class="foo">Item #7</li>
    <li class="bar">Item #8</li>
</ul>

我想得出以下结论:

<ul>
    <li class="foo">Item #1 <a>2 More Like This</a>
        <ul>
            <li class="foo">Item #2</li>
            <li class="foo">Item #3</li>
        </ul>
    </li>
    <li class="bar">Item #4</li>
    <li class="bar">Item #5</li>
    <li class="foo">Item #6 <a>1 More Like This</a>
        <ul>
            <li class="foo">Item #7</li>
        </ul>
    </li>
    <li class="bar">Item #8</li>
</ul>

简而言之,只要有2个或更多带有class =“ foo”的项目,就应该将它们组合在一起,直到达到非class =“ foo”的项目为止.然后,我可以使用链接显示或隐藏分组的项目.

解决方法:

这是一种可能性:

例如:http://jsbin.com/ipiki3/3/

$('ul > li.foo')
    .filter(function() {
        var $th = $(this);
        return $th.next('li.foo').length && !$th.prev('li.foo').length;
    })
    .each(function() {
        var $th = $(this);
        var len= $th.append('<a href="#"> more like this</a>')
                    .nextUntil(':not(li.foo)').wrapAll('<ul>').length;
        $th.next('ul').appendTo(this);
        $th.children('a').prepend(len);
    });

编辑:修复了len变量的错误,并添加一个示例.

说明:.filter()发生的事情是,它会将li.foo元素的范围缩小到组中的第一个元素(在它之后至少有一个li.foo,之前没有一个).

然后使用.each()附加< a&gt ;,获取一个元素,直到到达不是li.foo的元素,并用< ul>包装这些元素.并返回使用length属性数量.

然后我们遍历到新的< ul>并将其附加到组中的第一个li.foo中.

最后,我们将存储在length属性中的数量放在< a>中.元件.

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...