Sort Select Options by Value Attribute Using jQuery

后端 未结 3 683
终归单人心
终归单人心 2020-12-14 10:19

Well, the title says it all. What I am doing is creating a featured product module. The drop down list of sizes is populated using JSON and I am using handlebars to render t

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-14 11:12

    const sort = (arr, p, o = "asc") => arr.sort((a, b) => {
      if (o !== "asc")[a, b] = [b, a];
      const isNum = typeof b[p] === "number";
      return (isNum ? Number(a[p]) - b[p] : String(a[p]).localeCompare(b[p]));
    });
    
    
    $.fn.sortChildren = function(op) {
      op = $.extend({
        by: "textContent",
        order: "asc"
      }, op);
      return this.each(function() {
        const i = $(this).prop("selectedIndex");
        $(this).html(sort($(this).children(), op.by, op.order)).prop({selectedIndex: i});
      });
    };
    
    
    // 1. example: sorting by value, order "asc" (default)
    $("#test_1").sortChildren({by: "value"});
    
    // 2. example: sorting by textContent (default), order "desc"
    $("#test_2").sortChildren({order: "desc"});
    
    
    
    • z
    • -20
    • ab
    • 100
    • 1
    • 00
    • 10
    • Ab
    • 0.1

提交回复
热议问题