从单独的jQuery对象创建jQuery对象集合 [英] Create a jQuery object collection from separate jQuery objects

查看:59
本文介绍了从单独的jQuery对象创建jQuery对象集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$.fn.sortByDepth = function() {
    var ar = [];
    var result = $([]);

    $(this).each(function() {
        ar.push({length: $(this).parents().length, elmt: $(this)});
    });
    ar.sort(function(a,b) {
        return b.length - a.length;
    });
    for (var i=0; i<ar.length; i++) {
        result.add(ar[i].elmt);
    };
    alert(result.length);
    return result;
};

在此函数中,我尝试从单独的jQuery对象创建jQuery集合.我该怎么办?

In this function I try to create a jQuery collection from separate jQuery object. How can i do that ?

下面的代码不起作用:

result.add(ar[i].elmt);

jsfiddle: http://jsfiddle.net/hze3M/14/

The jsfiddle: http://jsfiddle.net/hze3M/14/

推荐答案

.add() 返回一个新的jQuery对象.更改此行:

.add() returns a new jQuery object. Change this line:

result.add(ar[i].elmt);

对此:

result = result.add(ar[i].elmt);

但这仍然行不通

从jQuery 1.4开始,.add()的结果将始终按文档顺序返回(而不是简单的串联).

As of jQuery 1.4 the results from .add() will always be returned in document order (rather than a simple concatenation).

因此,您只需要使用原始JS数组,将push()排序后的元素放入其中,然后整个$().

So you just use a vanilla JS array, push() the sorted elements into it, and then $() the whole thing.

其他代码清除:

$.fn.sortByDepth = function() {
    var ar = this.map(function() {
            return {length: $(this).parents().length, elt: this}
        }).get(),
        result = [],
        i = ar.length;


    ar.sort(function(a, b) {
        return a.length - b.length;
    });

    while (i--) {
        result.push(ar[i].elt);
    }
    return $(result);
};


var x = $('input').sortByDepth().map(function() {
    return this.id;
}).get().join(' - ');

$('#selection').text(x);

http://jsfiddle.net/mattball/AqUQH/.

这篇关于从单独的jQuery对象创建jQuery对象集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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