1

我正在尝试使用 JavaScript 为画廊获取图片,但遇到了问题。

$(document).ready(function() {

    var currentPage = 1;
    var totalPics = 2;
    var picPerPage = 1;
    intervalID = window.setInterval(function() {
          console.log(currentPage*picPerPage);
          if (totalPics > (currentPage*picPerPage)) {
        currentPage++;
        fetchNextPage(currentPage);
          } else {
        clearInterval(intervalID);
          }


    }, 2000);


});

由于某种原因,它会保持循环。我希望它停止那一刻currentPage * picPerPage > totalPics

我在 ubuntu 中使用 Firefox 3.6.8

更新

感谢你们。

我意识到问题是由于 fetchNextPage() 函数。

一旦我将其注释掉,循环问题就解决了。

但是,我需要 fetchNextPage 函数来运行 ajax 函数来获取另一组图像。

下面是功能

function fetchNextPage(currentPage) {

    newUrl = currentUrl + currentPage;

    $.ajax({
        url: newUrl ,
        success: function(data) {
            // append page 2 themes
            $('#themes-list').append(data);

        }
    });
}

那么我应该怎么做才能让我的无限画廊工作?

谢谢你。

4

3 回答 3

1

你的代码对我有用。我输入了 console.log() 而不是函数,并且没有intervalID正确定义。该函数是否有可能改变值?

var currentPage = 1;
var totalPics   = 2;
var picPerPage  = 1;

intervalID = window.setInterval(function() {

    console.log("A", currentPage*picPerPage);

    if (totalPics > (currentPage*picPerPage)) {
        currentPage++;
        console.log("B", currentPage);
    } else {
        console.log("C All Done");
        clearInterval(intervalID);
    }

}, 2000);

我得到的输出(OSX 上的 Chrome 5.0.375.127):

A 1
B 2
A 2
C All Done

更新:因此,对于您添加的代码,我有一些问题和意见:

function fetchNextPage(currentPage) {
    var newUrl = currentUrl + currentPage; // Added var declaration here. 
    $.ajax({
        url: newUrl ,
        success: function(data) {
            // append page 2 themes
            $('#themes-list').append(data);
        }
    });
}

所以这里缺少的是返回的数据......你能提供一个价值data是什么的例子吗?

于 2010-08-28T17:49:02.180 回答
0

尝试添加varbeforeintervalID = window.setInterval以正确定义 intervalID 变量。

于 2010-08-28T17:49:08.533 回答
0

亚历克斯的回答暗示了一个可能的问题。

此代码在任何地方都没有其他代码的测试环境中运行良好。

但是,intervalID被定义为全局变量。如果您在其他地方执行的代码也为 定义了一个值intervalID,那么它会在这个代码上到处乱踩。

用于var intervalID限制此变量的范围。

于 2010-08-28T17:54:38.333 回答