2012-12-14 84 views
2

我試圖將列表元素動態追加到已存在的列表中。將元素附加到列表

我在形式已經列表,

<ul id="test"> 
    <li class="testField">YYAAHOOOOOO<li> 
</ul> 

我想一個額外的項目添加到使用jQuery追加或之後......

我所做的是這個名單:

$(".testField").after("<li class='testField'>TEST MESSENGER</li>"); 

在函數追加後使用不起作用,after函數第一次正常工作,因爲只有一個類名爲testField的元素,但隨着列表的增長,after函數在將列表項添加到現有的所有元素,

爲了明確這一點,在第一次試驗,我會得到一個輸出:如果我現在嘗試在添加其他元素,例如<li class='testField'>GOOGLE</li>

<ul id="test"> 
    <li class="testField">YYAAHOOOOOO<li> 
    <li class='testField'>TEST MESSENGER</li> 
</ul> 

中,輸出將是這樣的:

<ul id="test"> 
    <li class="testField">YYAAHOOOOOO<li> 
    <li class='testField'>GOOGLE</li> 
    <li class='testField'>TEST MESSENGER</li> 
    <li class='testField'>GOOGLE</li> 
</ul> 

我想過使用ID,但我想有一個選項,從列表中刪除過的元素。所以,如果我嘗試添加到一個未定義的ID,它會返回錯誤。有無論如何找到列表中的第一個元素並將元素追加到第一個元素?

+0

在提問時,最好在早期包含最相關的信息。在上面的問題中,你已經非常徹底地掩蓋了一條非常重要的信息:*「無論如何找到列表中的第一個元素並將該元素附加到第一個元素??」*。 –

回答

5

嘗試:

$(".testField:first").after("<li class='testField'>TEST MESSENGER</li>"); 

這將確保你的第一個元素之後追加僅

+3

+1用於查看隱藏在問題底部的細節。 (那麼,並正確回答它!) –

+0

這看起來很好!!! :)讓我檢查 – user1371896

0

或者,你可以做到這一點沒有jQuery的:

var li = document.createElement('li');      // Create a List item. 
    li.setAttribute("class", "testfield");     // Set the li's class 
    li.addChild(document.createTextNode("Your Text Here!")); // Set the li's text 
document.getElementById("test").addChild(li);    // Append the li to the list 

它略多碼,是的,但它幾乎是jQuery所做的。 (快,太)

如果你想在列表中的第一li已經後添加新的UL,替換最後一行:

var ul = document.getElementById("test"); 
if(ul.children.length > 1){    // If the list has 2 or more children (li's) 
    ul.insertBefore(li, ul.children[1]); // Insert the new item before the second item in the list. 
}else{ 
    document.getElementById("test").addChild(li); 
} 

現在,爲什麼我張貼的答案,需要更多的代碼?
任何可以在jQuery中完成的事情都可以在原生JS中完成。我認爲在SO上有多個不同的答案是很好的,特別是如果他們使用不同的技術來做同樣的事情。這樣,用戶可以自己選擇:short'n easy(jQuery),或者如果他們不想使用庫,本機代碼。