【问题标题】:How to put page breaks in xml using jQuery如何使用 jQuery 在 xml 中放置分页符
【发布时间】:2012-08-20 15:34:44
【问题描述】:

我有一个 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 辆详细信息。

【问题讨论】:

    标签: jquery xml-parsing


    【解决方案1】:

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

    尽管如此

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

    Selecting the first "n" items with jQuery

    ..如果您真的想成为职业选手,请与knockoutjs 玩一下。

    【讨论】:

      【解决方案2】:

      您可以设置一个变量来定义您希望在每个页面中显示多少条记录,以及一个包含您当前所在页面的记录。然后使用 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();
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-18
        • 2016-10-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-07
        相关资源
        最近更新 更多