开发者

jQuery wrapping of classes

Hi I've got this list of li's, containing dynamic classes(not always the same). There's always a .connected class and two sets of "numberclasses".

<ul>
  <li class="connected 34 22"></li>
  <li class="connected 54 11"></li>
  <li class="connected 11 54"></li>
  <li class="connected 22 34"></li>
  <li class="connected 12 31"></li>
  <li class="connected 31 12"></li>  
</ul>

I want to wrap/sort the classes in groups like this:

<ul>
  <li>
    <ul>
      <!-- Group consisting elements with classes 12 or 31 -->
      <li class="connected 12 31">foo</li>
      <li class="connected 31 12">foo</li>
    </ul>
  </li>
  <li>
    <ul>
      <!-- Group consisting elements with classes 22 or 34 -->
      <li class="connected 34 22">foo</li>
      <li class="connected 22 34">foo</li>
    </ul>
  </li>
    ...
</ul>

How can i do this?

-- Update --

My sorting logic is that I want to wrap elements that contains the same classes.

I've tried something like $('.22').wrapAll('<ul/>'); but since the classes are gene开发者_开发百科rated and not static i can't find a way to do it.

-- Update 2 --

Think i know how I can do this. But I'm gonna need a little help.

First i push all class values from the list items to an array. Then remove all duplicates in that array. Later on iterate the array and wrap these array values in ul's. $('array[1]').wrapAll('<ul/>');

jsfiddle link


demo: http://jsfiddle.net/JX58j/

jquery

$(document).ready(function() {

    var classMap = [];

    $('.connected').each(function(idx) {
        var $this = $(this);

        // get the classes of each LI and sort them (It's easier to compare this way)
        var sortedClasses = $this.attr('class').split(' ').sort().toString().replace(/,/g, '-');

        // store the resulting sorted classes as data
        $this.data('grouping', sortedClasses);


        // add the 'grouping' to the classMap array if it isn't already in there
        if ($.inArray(sortedClasses, classMap) == -1) {
            classMap.push(sortedClasses);
        }
    });

    // create the ULs determined by the length of classMap
    for (i = 0; i < classMap.length; i++) {
        $('<ul>')
            .appendTo('#old-ul')
            .addClass(classMap[i]);           
    }

    // move the LIs from old UL to the new ULs
    $('.connected').each(function() {
        $this = $(this);
        $grouping = $this.data('grouping');
        $this.appendTo('ul.' + $grouping);
    });

    // wrap the ULs inside #old-ul in an LI tag so it validates
    $('#old-ul ul').wrap('<li />');


});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜