如何保存添加到jQuery匹配集的项目的顺序? [英] How to preserve order of items added to jQuery matched set?

查看:62
本文介绍了如何保存添加到jQuery匹配集的项目的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图以特定的顺序向jQuery对象添加元素。但是,结果集与DOM树相同。例如:

I am trying to add elements to a jQuery object in a specific order. However, the result set is ordered the same as the DOM tree. For example:

<div>one</div>
<span>two</span>
<p>three</p>

...

var $result = $("span").add("p").add("div");

我想要一个结果集,其中$ result [0]是跨度,$ result [1]是p等等。但是,它们与DOM中的命令相同。

I want a result set where $result[0] is the span, $result[1] is the p, and so on. However, they are ordered the same as in the DOM.

有没有另外一种方法来构建一个像我正在打算的jQuery对象,而不是.add()?

Is there another way to build out a jQuery object like I'm intending, other than .add()?

我知道我可以为它们指定一些数据属性来指定顺序,并按我的结果集进行排序。然而,这将需要在我的应用程序中发生几十次,并且必须分配顺序数据值,并且每次排序将是非常难看的,并且需要太长的时间来实现。

I'm aware that I could assign some data property to them to specify order, and sort my result set by that. However, this will need to happen dozens of times within my app and having to assign order data values and sorting each time will be really ugly, and would take too long to implement.

推荐答案

您可以使用本机 Array.push

$.fn.push = function(selector) {
    Array.prototype.push.apply(this, $.makeArray($(selector)));
    return this;
};

var $result = $("span").push("p").push("div");

演示: http://jsfiddle.net/ZUAcy/

您可能会认为jQuery在添加()但它实际上从函数返回一个pushStack来优化它的选择器: http://james.padolsey.com/jquery/#v=1.7.2&fn=jQuery.fn.add

You might think that jQuery does this behind the hood of add() but it actually return a pushStack from the function to optimize it’s selectors: http://james.padolsey.com/jquery/#v=1.7.2&fn=jQuery.fn.add

这篇关于如何保存添加到jQuery匹配集的项目的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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