Sorting Divs in jQuery by Custom Sort Order

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

    Appending (or prepending) the DOM nodes again will actually sort them in the order you want.

    Using jQuery, you just have to select them in the order you want and append (or prepend) them to their container again.

    $(['any', 'product', 'video'])
        .map(function(index, category)
        { 
             return $('[category='+category+']');
        })
        .prependTo('#input');
    

    Sorry, missed that you wanted to remove nodes not in your category list. Here is the corrected version:

    // Create a jQuery from our array of category names, 
    // it won't be usable in the DOM but still some 
    // jQuery methods can be used
    var divs = $(['any', 'product', 'video'])
    // Replace each category name in our array by the
    // actual DOM nodes selected using the attribute selector
    // syntax of jQuery.
        .map(function(index, category)
        { 
            // Here we need to do .get() to return an array of DOM nodes
            return $('[category='+category+']').get();
        });
    // Remove everything in #input and replace them by our DOM nodes.
    $('#input').empty().append(divs);
    
    // The trick here is that DOM nodes are selected 
    // in the order we want them in the end.
    // So when we append them again to the document,
    // they will be appended in the order we want.
    

提交回复
热议问题