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>");
        }
    }
}
]
4

2 回答 2

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() 之后

于 2013-03-31T10:26:41.740 回答
0

一个简单的方法是像这样使用jQuery 的:gt()选择器

$("#history tbody")
    .prepend('...')
    // using 9 here because gt() uses a zero-based index
    .find('tr:gt(9)').remove();
于 2013-03-31T15:29:25.397 回答