我有一个问题。我目前正在使用.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>");
}
}
}
]
答案 0 :(得分:2)
向#history tbody
添加元素后,确保此元素最多包含10行,即I.e。最多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()
之后答案 1 :(得分:0)
一种简单的方法是使用jQuery's :gt()
selector,如下所示:
$("#history tbody")
.prepend('...')
// using 9 here because gt() uses a zero-based index
.find('tr:gt(9)').remove();