.ajaxStop回调函数被执行多次

Arg*_*ote 8 javascript jquery flickr callback

我正在使用jQuery,但我的问题是,即使我在.ajaxStop回调函数中使用"page + = 1",我的页面变量也会增加几次,因为它在第一次使用后被执行了不止一次.我使用该变量作为传递给Flickr API的参数来获取特定的数据页面.

发生的事情是第一次调用该函数时,回调函数执行一次.然后,我从"更多"按钮调用相同的函数来获取下一组结果,但是那个时候函数被调用两次,下次调用三次,依此类推...这意味着我可以得到第1页, 2,4,7,11等......

我正在调用的AJAX函数基本上是.getJSON函数和一些在其回调方法中调用的额外.getJSON函数[在getPhotos(id)内部]

// This gets the user ID from a given Flickr user page URL and does some presentation stuff
function getUserID() {
    $("#moreRow").hide(350);

    var usr = document.getElementById('user').value
    var Req_addr = 'http://api.flickr.com/services/rest/?method=flickr.urls.lookupUser&api_key=' + API_key + '&url=http%3A%2F%2Fflickr.com%2Fphotos%2F' + usr + json
    $.getJSON(Req_addr, function(data) {
        // Once the user is known, data about its photos is requested    
        getPhotos(data.user.id)
    });

    // This hides the user data panel    
    $("#userInfo").hide(0);

    // This hides the settings panel    
    $("#settings").hide(0, function() {
        $("#loader").slideDown(750);
    });    

    // This is what displays the photos when all of the AJAX requests have received their responses (ajaxStop)
    $("#photos").ajaxStop(function() {
        // the page counter is incremented for the next page to be requested next time
        page += 1

        // Add the data for the newly obtained photos to the table
        addPhotosToTable()
    });
}
Run Code Online (Sandbox Code Playgroud)

关于我做错了什么的暗示?

你可以在这里看到整个来源:http://luisargote.com/flickr/javascript/argote_flickr.js

Nic*_*ver 10

您所看到的是因为.ajaxStop()附加了一个新的事件处理程序,并且每次都附加一个事件处理程序.只需将其移到外面(但仍在document.ready处理程序内),如下所示:

// This gets the user ID from a given Flickr user page URL and does some presentation stuff
function getUserID() {
    $("#moreRow").hide(350);

    var usr = document.getElementById('user').value
    var Req_addr = 'http://api.flickr.com/services/rest/?method=flickr.urls.lookupUser&api_key=' + API_key + '&url=http%3A%2F%2Fflickr.com%2Fphotos%2F' + usr + json
    $.getJSON(Req_addr, function(data) {
        // Once the user is known, data about its photos is requested    
        getPhotos(data.user.id)
    });

    // This hides the user data panel    
    $("#userInfo").hide(0);

    // This hides the settings panel    
    $("#settings").hide(0, function() {
        $("#loader").slideDown(750);
    });   
} 

// This is what displays the photos when all of the AJAX requests have received their responses (ajaxStop)
$("#photos").ajaxStop(function() {
    // the page counter is incremented for the next page to be requested next time
    page += 1

    // Add the data for the newly obtained photos to the table
    addPhotosToTable()
});
Run Code Online (Sandbox Code Playgroud)

替代方案是(如果由于某种原因#photos被吹走),将它留在函数内部并使用.one()如下:

$("#photos").one("ajaxStop", function() {
Run Code Online (Sandbox Code Playgroud)

这将运行处理程序一次,然后取消绑定它,给出你想要的效果......但除非元素在某处被破坏(听起来不像是这样)坚持在外面绑定它,没有理由做额外的工作.