【问题标题】:Having some trouble with the logic in my Javascript pagination code我的 Javascript 分页代码中的逻辑有一些问题
【发布时间】:2010-12-03 12:31:02
【问题描述】:
function Browse()
{
    this.offset = 10;
}

/*
 * @direction is either 'next' or 'prev'
 */
Browse.prototype.loadMore = function(direction)
{
    var _this = this;

    $.getJSON('/path/to/api?offset=' + this.offset, function(json)
    {
        _this.offset = (direction == 'next') ? _this.offset + 10 : _this.offset - 10;

        if (_this.offset > 10)
            previousButton.show();
        else
            previousButton.hide();
    });
}

这是基本代码。用户单击触发loadMore() 的链接。这个函数从offset开始拉取JSON数据。

此偏移量将根据他们当前的“页面”而变化。第一页的偏移量为 0。第二页将是 10。第三页 20 等等...

当他们来回导航时,这个偏移量应该相应地改变。问题是,它不是。我不明白为什么......

有什么想法吗?

【问题讨论】:

  • 您正在使用new Browse() 并挂钩实例的loadMore 方法,是吗?
  • 是的,这一切都被正确调用了。

标签: javascript pagination


【解决方案1】:

这是因为ajax调用需要时间来执行。

试试:

//...
var _this = this;

$.getJSON('/path/to/api?offset=' + this.offset, function(json) {
  //...
});
_this.offset = (direction == 'next') ? _this.offset + 10 : _this.offset - 10;
//...

这将在您的 ajax 调用中使用正确的值,并在 ajax 调用返回之前为下一次调用更改偏移量。如果同时调整了偏移量,您可能需要添加逻辑以忽略来自 ajax 调用的返回值。

【讨论】:

    猜你喜欢
    • 2021-09-25
    • 1970-01-01
    • 2017-11-15
    • 2020-10-31
    • 1970-01-01
    • 2016-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多