【问题标题】:YouTube JSON Pagination (jQuery)YouTube JSON 分页 (jQuery)
【发布时间】:2012-07-05 15:08:49
【问题描述】:

我正在尝试创建一个函数来加载 15 个新结果并将它们附加到之前使用 jQuery 加载的结果下方,有没有办法?

Javascript:

$(document).ready(function() {
    startindex = 1;
    loadmore = 15;

    src = "https://gdata.youtube.com/feeds/api/videos?category=games&alt=json-in-script&max-results=12&start-index=" + startindex;

    $.ajax({
        dataType: "jsonp",
        url: src,
        success: function(data, textStatus, jqXHR) {
            if (data.feed && data.feed.entry) {
                var list = [];

                $.each(data.feed.entry, function(i, e) {
                    list.push([
                        '<li class="video">',
                        '<img src="http://img.youtube.com/vi/' + e.id.$t + '/default.jpg" />',
                        '<a href="' + e.link[1].href + '">',
                        '<span>' + e.title.$t + '</span>',
                        '</a>',
                        '<span>' + e.author[0].name.$t + '</span>',
                        '</li>'
                    ].join(""));
                });

                $("#list").html(list.join(""));
            }
        }
    });

    function loadMore() {
        var startindex = parseInt(startindex) + parseInt(loadmore);
    }

});

HTML:

<ol id="list"></ol>

【问题讨论】:

  • 您需要增加起始索引,然后将新获取的结果附加到列表的底部。似乎是什么问题?

标签: jquery youtube pagination


【解决方案1】:

您要做的是将$(document).ready() 中的大部分代码转换为独立函数,然后在$(document).ready() 中调用该函数。该函数将采用两个参数,即开始位置和记录总数。

通过计算&lt;ol&gt; 中已有的项目数很容易获得起始位置,并且正在获取的记录总数(大概)不会改变。

$(document).ready(function() {
  startindex = 1;
  loadmore = 15;
  addMore(startindex, loadmore);

  $('#addmore').on('click', function(e) {
    e.preventDefault();
    addMore($('#list li').length, 15);
  });
});

function addMore(startindex, loadmore) {
  src = "https://gdata.youtube.com/feeds/api/videos?category=games&alt=json-in-script&max-results=" + loadmore + "&start-index=" + startindex;

  $.ajax({
    dataType: "jsonp",
    url: src,
    success: function(data, textStatus, jqXHR) {
      if (data.feed && data.feed.entry) {
        var $list = $('#list');

        $.each(data.feed.entry, function(i, e) {
          $list.append('<li class="video"><a href="' + e.link[1].href + '"><span>' + e.title.$t + '</span></a><span>' + e.author[0].name.$t + '</span></li>');
        });
      }
    }
  });
}
ol {
    list-style: decimal;
    margin-left: 2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

<ol id="list"></ol>
<a href="#" id="addmore">Add more</a>

http://jsfiddle.net/mblase75/PC6dn/1/

【讨论】:

    猜你喜欢
    • 2012-03-04
    • 2015-08-01
    • 1970-01-01
    • 2020-01-06
    • 2013-09-02
    • 2018-11-25
    • 1970-01-01
    • 1970-01-01
    • 2011-02-04
    相关资源
    最近更新 更多