【问题标题】:jquery sort ul element by the size of their childrenjquery 按子元素的大小对 ul 元素进行排序
【发布时间】:2013-09-19 12:18:24
【问题描述】:

关于排序 HTML 元素的一个简短问题。

如果有超过 10 个具有不同大小的孩子的无序列表。 他们是重新订购它们的简单方法吗?

HTML 示例:

<div id="wrapper">
    <ul>
        <li>One</li>
        <li>Two</li>
        <li>Three</li>
    </ul>
    <ul>
        <li>One</li>
        <li>Two</li>
        <li>Three</li>
        <li>Four</li>
        <li>Five</li>
    </ul>
    <ul>
        <li>One</li>
        <li>Two</li>
    </ul>
</div>

这就是我想要的:

    <div id="wrapper">
    <ul>
        <li>One</li>
        <li>Two</li>
    </ul>
    <ul>
        <li>One</li>
        <li>Two</li>
        <li>Three</li>
    </ul>
    <ul>
        <li>One</li>
        <li>Two</li>
        <li>Three</li>
        <li>Four</li>
        <li>Five</li
    </ul>
</div>

【问题讨论】:

  • 你能展示一下你目前尝试过的代码吗?

标签: jquery list function sorting children


【解决方案1】:

使用香草.sort() 相当容易。

  • 获取元素
  • 分离它们
  • 对它们进行排序
  • 将它们添加回 DOM

JavaScript

var $wrapper = $('#wrapper');

// Get children and detach
var children = $wrapper.children().detach();

// Sort them
children.sort(function(a, b) {
    // Compare amount of children
    return $(a).children().length - $(b).children().length;
});

// Add them back
$wrapper.append(children);

查看demo

【讨论】:

    【解决方案2】:

    基于 Tims 的回答,您可以将此功能包装在这样的 jQuery 函数中。

    $.fn.sortChildren = function(sortCb){
      this.children().detach().sort(sortCb).appendTo(this);
    };
    

    然后你可以像这样使用它,这提高了可读性和可重用性。

    var $wrapper = $('#wrapper');
    
    // Sort them
    $wrapper.sortChildren(function(a, b) {
        // Compare amount of children
        return $(a).children().length - $(b).children().length;
    });
    

    fiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-05
      • 2012-12-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多