将元素添加到jQuery集合的开头

时间:2014-01-29 10:50:37

标签: jquery

我想在jQuery集合的开头添加一些新元素。

add方法不按我想要的顺序添加元素。 http://jsfiddle.net/F8Z7v/1/

HTML

<p>p</p>
<i>i</i>
<b>b</b>    

javascript

// will be ordered according to the order they appear on the document
$('i').add('p').add('b');

// new elements will always appear at the end
$('i').add('<u id="u"></u>');
$('<u id="u"></u>').add('i');

// taking control of the ordering using raw arrays
var u = $('<u id="u"></u>').toArray();
u.push($('i')[0])
$(u);

最后一个选项有效,但有点难看。有更清洁的方法吗?

- 编辑 -

我的解决方案基于评论:

// Create the collection you want at the beginning
var newElems = $('<div></div>');

// Push new collection to it
newElems.push.apply(newElems, $('i, b, p'));

4 个答案:

答案 0 :(得分:2)

jQuery .add()不按该顺序添加元素。它在文档中提到过。

  

不要假设此方法将元素附加到现有元素   按照它们传递给.add()方法的顺序收集。什么时候   元素是同一文档的成员,即生成的集合   from .add()将按文档顺序排序;也就是说,按顺序排列   每个元素在文档中的外观。如果集合包含   来自不同文件的元素或不在任何文件中的元素   排序顺序未定义。使用a中的元素创建jQuery对象   定义良好的订单,使用$(array_of_DOM_elements)签名。

参考:http://api.jquery.com/add/

如果您想在收藏的最后添加,则必须只执行.push

答案 1 :(得分:2)

前段时间我遇到过类似的问题,并解决了这个问题:

$.fn.addTo = function(array) {
    var newArray = $(this).toArray();
    array.each(function(){
        newArray.push(this);
    });
    return $(newArray);
}

var items = $("i").add("b").add("p");
items = $("<ul></ul>").addTo(items);

此外,由于我返回jQuery对象,因此addTo()方法可以是方法链的一部分。

答案 2 :(得分:0)

你试过.prepend()吗?

  

将参数指定的内容插入每个内容的开头   匹配元素集合中的元素。

答案 3 :(得分:0)

您还可以使用.get()方法检索DOM节点并将其以数组形式传递给$(),例如:

$( $('#a').get().concat($('.b').get()).concat($('c').get()) );

或者如果它足以只获得第一个元素,那么这里是简化版

$([ $('#a')[0], $('.b')[0], $('c')[0] ]);

但请注意,在这种情况下,如果选择器不匹配则将未定义的值添加到数组中