Sorting Divs in jQuery by Custom Sort Order

后端 未结 6 629
名媛妹妹
名媛妹妹 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:13

    I wrote a jQuery plugin to do this kind of thing that can be easily adapted for your use case.

    The original plugin is here

    Here's a revamp for you question

    (function($) {
    
    $.fn.reOrder = function(array) {
      return this.each(function() {
    
        if (array) {    
          for(var i=0; i < array.length; i++) 
            array[i] = $('div[category="' + array[i] + '"]');
    
          $(this).empty();  
    
          for(var i=0; i < array.length; i++)
            $(this).append(array[i]);      
        }
      });    
    }
    })(jQuery);
    

    and use like so

    var category_sort_order = ['any', 'product', 'download'];
    $('#input').reOrder(category_sort_order);
    

    This happens to get the right order for the products this time as product1 appears before product2 in the original list, but it could be changed easily to sort categories first before putting into the array and appending to the DOM. Also, if using this for a number of elements, it could be improved by appending all elements in the array in one go instead of iterating over the array and appending one at a time. This would probably be a good case for DocumentFragments.

提交回复
热议问题