Sorting Divs in jQuery by Custom Sort Order

后端 未结 6 631
名媛妹妹
名媛妹妹 2021-01-31 11:35

I\'m trying to re-sort the child elements of the tag input by comparing their category attribute to the category order in the Javascript variable category_sor

6条回答
  •  温柔的废话
    2021-01-31 12:10

    It's seems fairly direct to use the sort method for this one:

    var category_sort_order = ['any', 'product', 'download'];
    
    // select your categories
    $('#input > div')
    
      // filter the selection down to wanted items
      .filter(function(){
        // get the categories index in the sort order list ("weight")
        var w = $.inArray( $(this).attr('category'), category_sort_order );
        // in the sort order list?
        if ( w > -1 ) {
          // this item should be sorted, we'll store it's sorting index, and keep it
          $( this ).data( 'sortindex', w );
          return true;
        }
        else {
          // remove the item from the DOM and the selection
          $( this ).remove();
          return false;
        }
      })
    
      // sort the remainder of the items
      .sort(function(a, b){
        // use the previously defined values to compare who goes first
        return $( a ).data( 'sortindex' ) - 
               $( b ).data( 'sortindex' );
      })
    
      // reappend the selection into it's parent node to "apply" it
      .appendTo( '#input' );
    

    If you happen to be using an old version of jQuery (1.2) that doesn't have the sort method, you can add it with this:

    jQuery.fn.sort = Array.prototype.sort;
    

提交回复
热议问题