0

我有一个 XML 文件“data.xml”,其中包含大约 80 辆汽车的详细信息(每辆汽车有 4 个子节点)。通过 Jquery 解析时,整个结果都出现在一个页面中,导致页面非常大。脚本代码为:

$(document).ready(function() {
    $('#car').click(function() {
        $.get('data.xml',function(data){
            $('#content').empty();
            $(data).find('car').each(function(){
                var $car = $(this);
                var html = '<div class="data">';                      
                html += '<b>' + $car.attr('company') + '</b>';
                html += '<div class="product">' + $car.find('product').text() + '</div>';
                html += '<div class="color">' + $car.find('color').text() + '</div>';
                html += '<div class="type">' + $car.find('type').text() + '</div>';
                $('#content').append(html);
            });                        
        });
        return false;
    });
});

我需要的是只有 8 辆汽车的详细信息应该出现在该页面中,并通过单击“转到下一页”在后续页面中显示进一步的 8 辆详细信息。

4

2 回答 2

0

最干净的选择是每 8 辆车执行一次 AJAX 调用 - 因为您不想在一次调用中加载太多数据。

尽管如此

  • 将您的 XML(或对象)存储在可以重复使用的地方
  • 使用计数器变量等,指示第一个可见项目的索引
  • 创建一个显示项目 n 直到 n+8 的更新方法(参见下面的 URL)
  • 此函数应清除 #content DIV 的内容(因为您正在使用 append 方法)

使用 jQuery 选择前“n”个项目

..如果您真的想成为专业人士,请使用knockoutjs玩一下。

于 2012-08-20T15:55:05.907 回答
0

您可以设置一个变量来定义您希望在每个页面中显示多少条记录,以及一个包含您当前所在页面的记录。然后使用 jQuery 的 slice() 方法只选择你想要的记录。然后,当单击下一个按钮时,增加页码并再次调用您的函数。您可能应该对此进行优化以不每次都调用重新加载 XML,并添加一些检查以确保您不会超过可用记录的总数,但您应该了解情况。

// init your variables
var currentPageIndex = 0;
var recordsPerPage = 8;

function showRecords() {
    // load your xml
    var currentRecordIndex = currentPageIndex * recordsPerPage;
    $(data).find('car').slice(currentRecordIndex, currentRecordIndex + recordsPerPage).each(function(){
        // do your processing 
    });                        
}

$("#next").click(function(e) {
    e.preventDefault();
    currentPageIndex++;
    showRecords();
});
于 2012-08-20T16:01:26.810 回答