jQuery sort elements using data id

前端 未结 3 1204
我寻月下人不归
我寻月下人不归 2020-11-28 11:50

I have an HTML structure as follows:

相关标签:
3条回答
  • 2020-11-28 12:16

    You can use dataset property which stores all of the custom data-* attributes of an element, it returns a string, in case that you want to convert the string to a number you can use parseInt or + operator.

    $('.clist div').sort(function(a,b) {
         return a.dataset.sid > b.dataset.sid;
    }).appendTo('.clist');
    

    http://jsfiddle.net/CFYnE/

    And yes, your code works here, http://jsfiddle.net/f5mC9/

    Edit: Please note that IE10! and below do not support the .dataset property, if you want to support all browsers you can use jQuery's .data() method instead:

    $('.clist div').sort(function(a,b) {
         return $(a).data('sid') > $(b).data('sid');
    }).appendTo('.clist');
    
    0 讨论(0)
  • 2020-11-28 12:16
    $('.clist div').sort(function(a,b) {
         return parseInt(a.dataset.sid) - parseInt(b.dataset.sid);
    }).appendTo('.clist');
    
    0 讨论(0)
  • 2020-11-28 12:30

    A more generic function to sort elements using jQuery:

    $.fn.sortChildren = function (sortingFunction: any) {
    
        return this.each(function () {
            const children = $(this).children().get();
            children.sort(sortingFunction);
            $(this).append(children);
        });
    
    };
    

    Usage:

    $(".clist").sortChildren((a, b) => a.dataset.sid > b.dataset.sid ? 1 : -1);
    
    0 讨论(0)
提交回复
热议问题