如何防止在最后一次调用完成之前执行事件

时间:2011-10-22 18:17:45

标签: jquery

我有这个jQuery事件:

$('#button-next').bind('click', function() {
    $.ajax({
        type: "GET",
        dataType: "json",
        url: 'index.php?route=product/category/display&cat=any&limit='+p+',1',
        cache: false,
        success: function(data) {
            var text = data.output;
            goForward('scroller', text);
            p++;
        }
    });
});

将新项目插入列表并删除最后一项。问题是如果用户开始如此快速地点击按钮,它会搞砸。我需要一种方法来防止在最后一个完成之前的新呼叫。

2 个答案:

答案 0 :(得分:2)

您可以使用.one()方法订阅点击操作:

$('#button-next').one('click', process);

您可以在此处定义process函数:

function process() {
    $.ajax({
        type: 'GET',
        dataType: 'json',
        url: 'index.php',
        cache: false,
        data: { 
            route: 'product/category/display', 
            cat: 'any', 
            limit: p + ',1' 
        },
        success: function(data) {
            var text = data.output;
            goForward('scroller', text);
            p++;
            // we rebind the click event once again
            $('#button-next').one('click', process);
        }
    });
}

答案 1 :(得分:1)

单击时禁用按钮并在完成ajax后启用它

            $('#button-next').bind('click', function() {
                $('#button-next').attr('disabled', 'disabled');
                $.ajax({
                    type: "GET",
                    dataType: "json",
                    url: 'index.php?route=product/category/display&cat=any&limit='+p+',1',
                    cache: false,

                    success: function(data) {
                            $('#button-next').removeAttr('disabled')
                            var text = data.output;
                            goForward('scroller', text);
                            p++;
                    }
                });
            });
相关问题