【问题标题】:Sort DIVs alphabetically without destroying and recreating them?按字母顺序对 DIV 进行排序而不破坏和重新创建它们?
【发布时间】:2015-07-07 10:57:03
【问题描述】:

我希望能够通过单击按钮对我页面上的一堆div 元素进行排序。

都有简单的文字内容,例如:

<div class='sortme'>
    CCC
</div>
<div class='sortme'>
    AAA
</div>
<div class='sortme'>
    BBB
</div>
<div class='sortme'>
    DDD
</div>

当用户点击一个按钮时,它们应该按字母顺序重新排列。显然有很多方法可以做到这一点,最明显的是我们可以将所有内容放入一个数组中,对数组进行排序并在此基础上重新创建 HTML。

这是此类解决方案的一个示例:

http://jsfiddle.net/hibbard_eu/C2heg/

但是,如果有很多代码已经在使用,这不会很好,我希望能够简单地移动 div 而不会做任何破坏性的事情。这可能吗?

【问题讨论】:

标签: javascript jquery


【解决方案1】:
  1. 使用sort()对元素数组进行排序
  2. 使用appendTo() 重新附加(处于排序状态)

$('.sortme').sort(function(a, b) {
  if (a.textContent < b.textContent) {
    return -1;
  } else {
    return 1;
  }
}).appendTo('body');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class='sortme'>
  CCC
</div>
<div class='sortme'>
  AAA
</div>
<div class='sortme'>
  BBB
</div>
<div class='sortme'>
  DDD
</div>

【讨论】:

  • detach() 我猜是没用的,你应该将它附加到特定的容器,而不是主体。顺便说一句,我会修剪textContent,以防万一
  • @A.Wolff,嗯嗯很好的观察。感谢您的提示
  • 简化:$('.sortme').sort(function(a, b) { return a.textContent
【解决方案2】:

即使没有 jQuery 也可以很简单地完成

function sortThem(s) {
    Array.prototype.slice.call(document.body.querySelectorAll(s)).sort(function sort (ea, eb) {
        var a = ea.textContent.trim();
        var b = eb.textContent.trim();
        if (a.textContent < b.textContent) return -1;
        if (a.textContent > b.textContent) return 1;
        return 0;
    }).forEach(function(div) {
        div.parentElement.appendChild(div);
    });
}
// call it like this
sortThem('div.sortme');

element.appendChild(x) 添加 x 作为 element 的最后一个子元素,如果 x 存在于 DOM 中,则将其从当前位置移出,所以,否需要任何体操将其删除在一个地方并添加到另一个地方

【讨论】:

  • @PixelPimp - 嗯? 5岁的答案,你引用代码的最后两行作为评论......有什么意义吗?
【解决方案3】:

使用追加。

var $divs = $("div.box");

$("div.box").on("click", function (e) {
    alert("I'm an original");
});

$('#alphBnt').on('click', function () {
    var alphabeticallyOrderedDivs = $divs.sort(function (a, b) {
        return $(a).find("h1").text() > $(b).find("h1").text();
    });

    alphabeticallyOrderedDivs.each(function (i, item) {
        $("#container").append(item);
    });
});

$('#numBnt').on('click', function () {
    var numericallyOrderedDivs = $divs.sort(function (a, b) {
        return $(a).find("h2").text() > $(b).find("h2").text();
    });

    numericallyOrderedDivs.each(function (i, item) {
        $("#container").append(item);
    });
});

Fiddle

【讨论】:

    猜你喜欢
    • 2021-10-07
    • 2011-08-29
    • 1970-01-01
    • 2018-01-27
    • 2017-05-22
    • 1970-01-01
    • 2018-11-19
    相关资源
    最近更新 更多