且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

根据数据属性将列表项目分组到子列表中

更新时间:2023-02-17 17:58:24

b
$ b

  $(function(){var sortable = $(#sortable1),content = $(#content); var groups = []; sortable .find(li)。each(function(){var group = $(this).data(group); if($。inArray(group,groups)=== -1){groups.push( groupUl = $(< ul>);}}; ).append(liElements); content.append(groupUl);});});  

 < script src =https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js>< / script>< ul id =sortable1> < li data-group =A>测试< / li> < li data-group =A> test1< / li> < li data-group =B> test2< / li> < li data-group =B> test3< / li> < li data-group =C> test4< / li>< / ul>< div id =content> < / div>  



我希望我没有误解你。


I want to append the <li> from one <ul> to another <ul> that's created on the fly. I want to group the list-items into new sub-lists based on their data-group attribute.

<ul id="sortable1">
    <li data-group="A">test</li>
    <li data-group="A">test1</li>
    <li data-group="B">test2</li>
    <li data-group="B">test3</li>
    <li data-group="C">test4</li>
</ul>

Basically I'm trying to loop through this list and grap all <li> from each group, and then move it to another <ul>.

This is what I have so far, but I'm not getting the expected results. I have done this in Excel in the past but can't get it to work with jQuery.

var listItems = $("#sortable1").children("li");
listItems.each(function (idx, li) {
    var product = $(li);
    //grab current li
    var str = $(this).text();

    if (idx > 0) {
        //append li
        str += str;
        if ($(this).data("group") != $(this).prev().data("group")) {
            //I should be getting  test and test1. 
            //but alert is only giving test1 test1. 

            alert(str);
            //need to break into groups
            //do something with groups
        }
    }
});

How about something like this:

$(function() {
    var sortable = $("#sortable1"),
        content = $("#content");

    var groups = [];
    sortable.find("li").each(function() { 
        var group = $(this).data("group");
        if($.inArray(group, groups) === -1) {
            groups.push(group);
        }
    });
    
    groups.forEach(function(group) { 
        var liElements = sortable.find("li[data-group='" + group + "']"),
            groupUl = $("<ul>").append(liElements);
        content.append(groupUl);
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="sortable1">
    <li data-group="A">test</li>
    <li data-group="A">test1</li>
    <li data-group="B">test2</li>
    <li data-group="B">test3</li>
    <li data-group="C">test4</li>
</ul>

<div id="content">    
</div>

I hope I didn't misunderstand you.