2012-12-27 45 views
1

我的客戶端代碼從服務器獲取一些數據,然後將數據呈現在屏幕上。Javascript:附加在列表的開頭

什麼'追加'確實是它把最新的數據放在列表的最後,而我想要最新的數據顯示在列表的頂部。我正在尋找像之前追加或追加在開始

任何幫助,將不勝感激。

<script> 
    for(var i = 0 ; i < data.length; i++){ 
     $('#uls').append('<li><p>' + data[i].summary + '</p></li>'); 
    } 
</script> 

<body> 
    <div id="main"> 
     <ul id="uls"></ul> 
    </div> 
</body> 

回答

0

您可以使用插入指定的內容作爲第一個孩子這樣的方法「前加上」:

<script> 
    for(var i = 0 ; i < data.length; i++){ 
     $('#uls').prepend('<li><p>' + data[i].summary + '</p></li>'); 
    } 
</script> 

<body> 
    <div id="main"> 
     <ul id="uls"></ul> 
    </div> 
</body> 
+1

不是我!!適用於我。謝謝 –

+0

完美我喜歡你已經解決了你的問題@mangobug –

2

我認爲您在尋找prepend

您的代碼將變爲:

<script> 
    for(var i = 0 ; i < data.length; i++){ 
     $('#uls').prepend('<li><p>' + data[i].summary + '</p></li>'); 
    } 
</script> 

<body> 
    <div id="main"> 
     <ul id="uls"></ul> 
    </div> 
</body> 
0

使用innerHTML這個

document.getElementById('uls').innerHTML="<li><p>"+data[i].summary+"</p></li>"+document.getElementById('uls').innerHTML 
0

你並不真正需要的jQuery此:

var ul = document.getElementById('uls'); // Get the ul 

var li = document.createElement('li'); // Create a <li> 
var p = document.createElement('p'); // Create a <p> 

li.appendChild(p); // Add the <p> to the <li> 
p.appendChild(document.createTextNode(data[i].summary)); // Add the text to the <p> 

ul.insertBefore(li, ul.childNodes[0]); // Add the <li> to the first position of the <ul>. 

Working Sample

我知道它比jQuery選項更多的代碼,但它也更快。

0

如果你確實需要使用jQuery,我建議做這種方式:

<script> 
var i, 
    dataMaxIndex, 
    ulsContent = ""; 
dataMaxIndex = data.length - 1; 
if (dataMaxIndex >= 0) { 
    for (i = dataMaxIndex; i >= 0; i = i - 1) { 
     ulsContent = ulsContent + '<li><p>' + data[i].summary + '</p></li>'; 
    } 
    $(document.getElementById('uls')).prepend(ulsContent); 
} 
</script> 

一些代碼的改進: - 是更好地使用的document.getElementById選擇,並把它包裝成jQuery的 - 插入所有HTML內容一次(不是每次迭代);

例如:http://jsfiddle.net/8RLcx/