【问题标题】:Wrap List elements by class name按类名包装列表元素
【发布时间】:2016-03-11 00:33:06
【问题描述】:

我已经问过相关的答案,但和这个不一样问题:How to make new Div inside list items
我的问题是如何打破列表项并从列表项中添加新的类查找,示例如下?

主 HTML: Fiddle

<div class="widget-content">
<ul>
<li><a class="label1" href="/lorem">lorem</a> Test Content</li>
<li><a class="label1" href="/lorem">lorem</a> Test Content</li>
<li><a class="label1" href="/lorem">lorem</a> Test Content</li>

<li><a class="label2" href="/lorem">lorem</a> Test Content</li>
<li><a class="label2" href="/lorem">lorem</a> Test Content</li>
<li><a class="label2" href="/lorem">lorem</a> Test Content</li>
</ul>
</div>

我想像这样按类分解列表项:

<div class="widget-content">

<ul class="label1"> <!--add class find from list-->
<li><a class="label1" href="/lorem">lorem</a> Test Content</li>
<li><a class="label1" href="/lorem">lorem</a> Test Content</li>
<li><a class="label1" href="/lorem">lorem</a> Test Content</li>
</ul>

<ul class="label2"> <!--add class find from list-->
<li><a class="label2" href="/lorem">lorem</a> Test Content</li>
<li><a class="label2" href="/lorem">lorem</a> Test Content</li>
<li><a class="label2" href="/lorem">lorem</a> Test Content</li>
</ul>

</div>

我的意思是按类分解列表项并将类添加到父级ul 从上面给出的列表项示例中查找。如何通过 Jquery/JS 简单地做到这一点?
提前致谢。

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    jsBin demo

    $(".widget-content").each(function(){
    
      var $li = $(this).find("li").unwrap(); // unwrap removes the old UL wrapper
      var uniq = [];
    
      // Create a collection of unique "label*" classes:
      $li.find("[class^=label]").attr("class", function(i, v){
        if(!~$.inArray(v, uniq)) uniq.push(v);
      });
    
      // Group LI by A class, and wrap into a new UL with the same class
      $.each(uniq, function(i, klas){
        $("a."+klas).closest("li").wrapAll($("<ul/>",{class:klas}));
      });
    
    });
    

    【讨论】:

    • 但是如何按类分解列表项?请提供链接。
    • 好的,任何小提琴链接示例,试图按类打破列表项
    猜你喜欢
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-23
    • 1970-01-01
    • 2022-03-07
    • 2018-07-06
    • 2018-07-30
    相关资源
    最近更新 更多