我想在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'));
你能詳細說明爲什麼你必須依賴jQuery對象中元素的內部順序嗎? –
爲什麼你要控制檯,.add方法? – Praveen
@FrédéricHamidi我正在將現有集合與新元素集合合併,以便將它們插入到DOM中。有必要將它們合併,因爲我必須組合這些元素。 –