如何在JavaScript变量中反转HTML DOM元素的顺序?

时间:2012-06-25 20:51:43

标签: javascript jquery

我需要打印出插入我数据库的收据,最新的收据应该在我的页面顶部。但是当我查询我的数据库时,我将所有数据存储在var中,自然它会使我最早插入到页面顶部的数据,我该如何反转?

function querySuccess(tx, results){
    if(results.rows.length == 0)
    {
        $("#ReceiptsList").html("<p>You have no receipts captured yet</p>");
    }
        else
    {
        var s = "";
        for(var i = 0; i<results.rows.length; i++)
        s += "<a href='edit.html?id="+results.rows.item(i).id+"'><strong><font size = 3> " + results.rows.item(i).name +"<font></strong>" + "&nbsp;&nbsp;&nbsp;&nbsp;<font size = 1>Date:" +results.rows.item(i).date +  "<font></a> ";
    }
        //I tried s.reverse(); but didn't work, nothing was showed on the page
        $("#ReceiptsList").html(s);
}

2 个答案:

答案 0 :(得分:5)

扭转循环?从最后开始?

for(var i = results.rows.length-1; i>=0; i--)

或者附加字符串的开头,而不是结尾!

或让服务器首先返回正确的顺序。

答案 1 :(得分:0)

function querySuccess(tx, results){
if(results.rows.length == 0)
{
    $("#ReceiptsList").html("<p>You have no receipts captured yet</p>");
}
    else
{
    var s = "";
    for(var i = results.rows.length-1; i>=0; i--)
    s += "<a href='edit.html?id="+results.rows.item(i).id+"'><strong><font size = 3> " + results.rows.item(i).name +"<font></strong>" + "&nbsp;&nbsp;&nbsp;&nbsp;<font size = 1>Date:" +results.rows.item(i).date +  "<font></a> ";
}

    $("#ReceiptsList").html(s);
}