开发者

Recursive jQuery load command

开发者 https://www.devze.com 2023-02-04 06:35 出处:网络
In a previous post about Recursive jQuery load command the proposed code works but has some limitations.Here is the code that had been proposed and the link:

In a previous post about Recursive jQuery load command the proposed code works but has some limitations. Here is the code that had been proposed and the link:

function loadTree($element) {
  $element.each(function(){
    this.load('url', function(){
      loadTree(this.find('.children'));
    });
  });
}

loadTree($('#content'));

The problem with the above code is that if loading is not successful, the recursive loop terminates. In my case I am loading images one after the other and I get the image URLs from the database via an AJAX call. If for some reason an image URL is incorrect, the recursion will stop and I do not want this thing to happen. The rest of the images must be loaded no matter what because if I have a hundred image paths where all of them are valid except for the first one, then all 100 will not show up.

I also have another related problem. Basically I was retrieving 7 image urls via ajax, I was then forming 7 html image tags in a string and then calling the load event with that string just once: all of this in an attempt to reduce the number of browser requests. Therefore I want the load event callback to trigger after all 7 images are loaded. However when I try this, the load event callback triggers for each and every image. Any ideas on how to trigger a callback when all items have been loaded (b开发者_JS百科e it a successful load or not; an attempt to load).

Thanks


I haven't been able to test this, but it should put you on the right track to cover your question.

With the complexity of what you are doing you should move to the more verbose $.ajax function, as it gives more callback functions at each time and tests for failure.

   function loadTree(element) {
    var elementsQueried = 0;
    $(element).each(function(index, value){

        $.ajax({
            url: 'url',
            success: function(returnValue){
                $(value).html(returnValue); //if successful ajax assign the returned html to the element
                loadTree($(value).find('.children')); //then continue searching the child tree
            },
            error: function(request,error) {
                $(value).html('File not found'); //else give some useful error message, but dont keep searching child tree

            },
            complete: function(){
                elementsQueried++;
                if (elementsQueried==$(element).length){
                    //callback
                }
            }
        });

    });
   }

Like I said I haven't been able to test it so there may be some issues, in particular with the scope of the elementsQueried var and how that is handled with the recursion.

0

精彩评论

暂无评论...
验证码 换一张
取 消