基于DOM值的DOM对象的JQuery排序数组 [英] JQuery Sort Array of DOM Objects based off DOM values

查看:98
本文介绍了基于DOM值的DOM对象的JQuery排序数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用Jquery两年了,但是这个问题使我的工作望尘莫及.

I've been using Jquery for a couple of years but this question pushes my limits.

我有一个基于多个条件进行排序的DOM对象数组.我这样创建数组:

I have an Array of DOM Objects that I'm sorting based of a number of conditions. I create the array like this:

var conversationsInBoxMemberUserIDsArray = $('#conversationsInBoxMessagesWrapperDIV').children().map(function() {return $(this);}).get();

每个推送到数组的项目都是DOM的一部分.或者引用DOM的某个部分可能是一种更好的说法.我可以看到它指的是DOM的一部分,因为当我更改顺序并将此数组附加到根DIV时,所有对象(包含内容的DIV)的顺序都会在视觉上发生变化. DOM部分喜欢这样(缩减版本以节省时间/空间):

Each item pushed onto the array is a section of DOM. Or a reference to a section of DOM could be a better way to say it. I can see this it refers to a section of DOM because when I change the order and append this array back to the root DIV the order of all the objects (DIV's with content) within changes visually. The section of DOM likes this (cut down version to save time/space):

<divContainer>
  <div_sub1>
    <div sub2>
      <h3 class="name">Adam</h3>
    </div>
  </div>
</div>

我要基于$(.name)类的DOM element.text值对DOM对象数组进行排序

I want to sort this array of DOM objects based off the DOM element.text value with class $(.name)

例如:A-Z基于此名称的文本值-例如:Ben之前的Adam

eg: A-Z based off this this text value of name - eg: Adam before Ben

这可能吗?

可以使用标准排序功能完成此操作吗?

Can this be done using the standard sort function:

theArray.sort(function(a, b){
   if (a.Field2 == b.Field2) return 0;
   if (a.Field2 < b.Field2) return -1;
   return 1;
 });

任何建议将不胜感激. Unix时间戳也需要做同样的事情.

any advice would be greatly appreciated. Will also need to do the same off a unix timestamp.

adam

推荐答案

尝试类似

var $ct = $('#container'),
    $items = $ct.children(),
    array = $items.get();

array.sort(function (o1, o2) {
    return $(o1).find('.header h3').text().localeCompare($(o2).find('.header h3').text())
});

$ct.append(array)

演示:小提琴

对值进行一些缓存后,您可以尝试

After doing some caching of values, you can try

var $ct = $('#container'),
    $items = $ct.children(),
    array = $items.map(function () {
        var $this = $(this);
        $this.data('header', $.trim($this.find('.header h3').text()))
        return $this;
    }).get();

array.sort(function (o1, o2) {
    return o1.data('header').localeCompare(o2.data('header'))
});

$ct.append(array)

演示:小提琴

这篇关于基于DOM值的DOM对象的JQuery排序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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