2013-03-31 37 views
2

我有問題。我目前使用的是.prepend(),它將較舊的表格行推到底部,而新的表格行出現在頂部。但是,我必須將錶行數限制爲10,這樣做,一旦.prepend()達到10行,最後一行將出現在表的底部,隨後反過來再次工作。我想知道一種方式,在將較舊的行推到底部時,新行將永久出現在<tbody>的頂部。這裏是我的一些參考代碼。用固定行數將表格行推到底部

// show the keys currently held in the specified type of storage in the 

// specified table 

function showStorageKeys(type, table, table1) { 

// get the specified type of storage, i.e. local or session 
var storage = window[type + 'Storage']; 
// remove the rows in the specified table before we start 
$(table + " > tbody > tr").remove(); 
$(table1 + " > tbody > tr").remove(); 
// loop through the existing keys in the storage and add them to the TBODY 
// element as rows 
for (var i = 0; i < storage.length; i++) { 
    var key = storage.key(i); 
    if ((key == "0") || (key == "1") || (key == "2") || (key == "3") || (key == "4") ||    (key == "5") || (key == "6") || 
      (key == "7") || (key == "8") || (key == "9")) { 
     var details = storage.getItem(key); 
     details = details.split(";"); 
     var lat = details[0]; 
     var long = details[1]; 
     var zoom = details[2]; 
     var time = details[3]; 
     var address = details[4]; 
     //var date = details[5]; 
     if ((address == undefined) || (time == undefined) || (address == "")) { 
      document.getElementById("dummy").value = ""; 
     } 
else { 
      $("#history tbody").prepend(
"<tr>" + "<td width='5%'>" + time + "</td>" +"<td>" + "<a href='JavaScript:getSite(" + lat + ',' + long + ',' + zoom + ")'>" + address +"</a>" +</td>" + "<td width='15%'>" + "<input type='submit' value='Remove' onclick='removeItem(\"" + type + "\", \"" + key + "\")'/>" + "</td>" + "</tr>"); 
     } 
    } 
} 
] 

回答

2

將一個元素增加到#history tbody,之後,以確保該元件具有最大的10行,即最多10個孩子的,你可以這樣做:

while($("#history tbody").children().length > 10){ 
    $("#history tbody").children().last().remove() 
} 

和你的插入新行代碼,這個代碼後直接放置。

另外,要注意的是,如果元素的查詢對象經常用作查詢函數的調用,每次可能會很慢,那麼通常會將元素的查詢對象存儲在變量中,所以在我給出的示例中以上,並在代碼中,你應該考慮此因素出來,它會快得多:

var history_tbody = $("#history tbody") 
... 
history_tbody.prepend(...) 

while(history_tbody.children().length > 10){ 
    history_tbody.children().last().remove() 
}  

,並嘗試讓你的history_tbody的定義發生一次,如在你的文件的開始,的document.ready()

0

經過簡單的方法是使用jQuery's :gt() selector這樣的:

$("#history tbody") 
    .prepend('...') 
    // using 9 here because gt() uses a zero-based index 
    .find('tr:gt(9)').remove();