按字母顺序排序DIV而不破坏和重新创建它们? [英] Sort DIVs alphabetically without destroying and recreating them?

查看:77
本文介绍了按字母顺序排序DIV而不破坏和重新创建它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够通过点击按钮在我的页面上排序一堆 div 元素。

I'd like to be able to sort a bunch of div elements on my page with the click of a button.

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

All of them have simple text content, for example:

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

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

When the user clicks a button, they should be rearranged in alphabetical order. Obviously there's a number of ways to do this, most obviously we can get all the contents into an array, sort the array and recreate the HTML based on that.

这是这种解决方案的一个例子:

This is an example of such a solution:

http://jsfiddle.net/hibbard_eu / C2​​heg /

然而,对于已经使用的大量代码,这不会很好,我希望能够简单地移动没有做任何破坏性的事情。这可能吗?

However, this wouldn't play nice with a lot of code already being used, and I was hoping to be able to simply move the divs around without doing anything destructive. Is this possible?

推荐答案


  1. sort()

  2. 使用 appendTo() 重新附加(处于排序状态)

  1. Sort the element array with sort()
  2. Reattach(in their sorted state) with 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>

这篇关于按字母顺序排序DIV而不破坏和重新创建它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆