添加回调到$(xml).find(“..”)。每个

时间:2013-02-27 16:12:46

标签: javascript jquery

是否可以在此循环中添加回调?作为让应用知道“现在是时候做这个......”的一种方式......?

$(xml).find("book").each(function(){
    var id = $(this).find("id").text(); 
    var x = $(this).find("x").text();   
    var y = $(this).find("y").text();   
    var z = $(this).find("z").text();   

    hasItem(id, x, y, z, function(flag, id, x, y, z) {
        if(!flag) {
            //doing something
        }
    });
}); 

//add callback to tell me that all rows of xml has been read and hasItem is done reading?

1 个答案:

答案 0 :(得分:1)

即使是异步操作,为什么一旦完成就不调用函数?

function done(){
    // completed...
}
var total = $(xml).find("book").length;
$(xml).find("book").each(function(index, element){
    var id = $(this).find("id").text(); 
    var x = $(this).find("x").text();   
    var y = $(this).find("y").text();   
    var z = $(this).find("z").text();  
    hasItem(id, x, y, z, function(flag, id, x, y, z) {
        if(!flag) {
            //doing something
            if(total == index+1)
               done();
        }
    });
});