Sort a set of li tags alphanumerically

前端 未结 3 1270
轮回少年
轮回少年 2021-01-21 05:53

I\'ve been playing around trying to get a function that will sort a selection of li tags by their content but currently to no avail (at least no speed/accuracy);



        
3条回答
  •  粉色の甜心
    2021-01-21 06:37

    I'm not completely sure what your alphaNumSort function does, but a simple string comparison may be enough.

    var li = $('#licontainer li').get();
    
    // sort the list items based on the contents of a nested strong tag
    li.sort(function(a, b) {
        a = $('strong', a).text();
        b = $('strong', b).text();
    
        // you may want to process the text values further here, perhaps
        // running it through $.trim, reducing whitespace sequences with
        // a regular expression, or lower- or upper-casing letters to
        // make the comparison case-insensitive.
    
        return (a < b) ? -1 : ((a > b) ? 1 : 0);
    });
    
    // reinsert the list items in their new order
    $('#licontainer').append(li);
    

    This should be considerably faster than your temporary list method, as it performs fewer DOM operations. The use of native string comparisons should also be a fair bit faster than your current sorting algorithm, but if it is doing something specific that I have missed update the return statement to utilize it (keeping the preceding lines).

    return alphaNumSort(a, b);
    

    If this is still too slow you could likely improve performance even more by hiding the list before manipulating it, preventing the browser from performing unnecessary repaints.

    var li = $('#licontainer').hide().find('li').get();
    
    // ...
    
    $('#licontainer').append(li).show();
    

提交回复
热议问题