简体   繁体   English

如何保留添加到 jQuery 匹配集中的项目的顺序?

[英]How to preserve order of items added to jQuery matched set?

I am trying to add elements to a jQuery object in a specific order.我正在尝试按特定顺序将元素添加到 jQuery 对象。 However, the result set is ordered the same as the DOM tree.但是,结果集的顺序与 DOM 树相同。 For example:例如:

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

...

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

I want a result set where $result[0] is the span, $result[1] is the p, and so on.我想要一个结果集,其中 $result[0] 是跨度,$result[1] 是 p,依此类推。 However, they are ordered the same as in the DOM.但是,它们的顺序与 DOM 中的顺序相同。

Is there another way to build out a jQuery object like I'm intending, other than .add()?除了 .add() 之外,还有其他方法可以像我想要的那样构建 jQuery 对象吗?

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.但是,这将需要在我的应用程序中发生数十次,并且每次都必须分配订单数据值和排序将非常难看,并且需要很长时间才能实现。

You can use the native Array.push :您可以使用本机Array.push

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

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

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

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 在add()的引擎盖后面执行此操作,但它实际上从函数返回一个 pushStack 以优化它的选择器: http ://james.padolsey.com/jquery/#v=1.7.2&fn=jQuery.fn 。添加

This would work:这会起作用:

var $result = $([
    $('span')[0],
    $('p')[0],
    $('div')[0]
]);

From the docs on .add() :.add() 上文档

To create a jQuery object with elements in a well-defined order and without sorting overhead, use the $(array_of_DOM_elements) signature.要创建具有明确定义顺序的元素且没有排序开销的 jQuery 对象,请使用$(array_of_DOM_elements)签名。

the unordered array produced by the following code:以下代码生成的无序数组:

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

should transform into an ordered array with these lines of code:应该使用以下代码行转换为有序数组:

var result=$("span").get().concat($("p").get(),$("div").get());
var $result=$(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM