使用Javascript/Jquery根据类名称排序DIV [英] Ordering DIVs based on class name using Javascript/Jquery

查看:291
本文介绍了使用Javascript/Jquery根据类名称排序DIV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下HTML结构:

I have the following HTML structure:

<div id="container">
    <div>1</div>
    <div class="red">2</div>
    <div class="red">3</div>
    <div>4</div>
    <div>5</div>
    <div class="red">6</div>
    <div>7</div>
</div>

我本来不是运行一些Jquery来对div容器内的div进行排序的,方法是先对具有class ="red"的divs 进行排序,然后对不具有class ="red"的divs进行排序,因此最终结构应该是:

I wast to run some Jquery that will sort the divs inside the div container by ordering the divs first that have class="red", and then those that don't, so the final structure should be:

<div id="container">
    <div class="red">2</div>
    <div class="red">3</div>
    <div class="red">6</div>
    <div>1</div>
    <div>4</div>
    <div>5</div>
    <div>7</div>
</div>

有帮助吗?谢谢.

推荐答案

尝试一下:

 $(function(){
   var elem = $('#container').find('div').sort(sortMe);
   $('#container').append(elem);
 });

 function sortMe(a, b) {
        return a.className < b.className;
  }

演示

带有某些fadeIn/fadeout动画

var elem = $('#container').find('div').sort(sortByClass);

 function sortByClass(a, b) {
    return a.className < b.className;
 }

 var allElem = elem.get();
  (function append() {

    var $this = $(allElem.shift());

     $('#container').append(
                $this.fadeOut('slow'))
                         .find($this)
                             .fadeIn('slow', function () {
                                      if (allElem.length > 0) 
                                          window.setTimeout(append);
                            });
      })();

这篇关于使用Javascript/Jquery根据类名称排序DIV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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