去抖动点击AJAX链接

时间:2017-03-23 14:18:07

标签: javascript jquery ajax debounce

是否可以去除链接的点击?如果用户在pjax链接上点击次数过多,则会破坏新内容的负载。

$(document).on('click', 'a[data-pjax]', loadNewContent);

var $target = $('main.content section.context'),
$fake = $('main.fake'),
$fakeContext = $('main.fake section.context');

function loadNewContent() {

    event.preventDefault();

    var $this = $(this),
    url = $this.attr('href');

    $fake.addClass('is--loading');

    $.pjax({
        url: url,
        fragment: 'body',
        container: $fakeContext
    });

    $fake.one(transitionEnd, function() {
        $target.html($fake.find('section.context').html());
        $fake.removeClass('is--loading');
        $fake.off(transitionEnd);
    });

}

有什么想法?我尝试过这个,但它阻止了loadNewContent的触发。 (https://github.com/cowboy/jquery-throttle-debounce

$(document).on('click', 'a[data-pjax]', $.debounce(1000, true, function() {
    loadNewContent();
}));

1 个答案:

答案 0 :(得分:2)

这样的事情会起作用:

var callWaiting = false;
callAjax() {
  if(!callWaiting) {
    callWaiting = true;
    makeHttpCall(url, data, function(response) {callWaiting = false;});
    callWaiting = false;
  }
}