jQuery chaining .load() requests?

感情迁移 提交于 2019-12-01 21:02:04
dave

You would need to nest them in the callback functions to achieve this:

$('#example').load('./uri.ext #ID1', function() {
  $('#ID1').load('./uri.ext #ID2', function() {
    $('#ID2').load('./uri.ext #ID3', function() {
      // load successful
    });
  });
});

EDIT for ES6 standards:

 $('#example').load('./uri.ext #ID1', () => {
      $('#ID1').load('./uri.ext #ID2', () => {
        $('#ID2').load('./uri.ext #ID3', () => {
          // load successful
        });
      });
    });

Upvoted the question and the answer.

I'm providing a slightly more elegant solution using a recursive call in case others want to build on it. Note that this doesn't directly answer the context of the original question. It's in the context of my own solution, but the idea is the same.

var App = App || {};

App.Quiz = (function ($) {
    "use strict";

    var _templates = [{ target: "#quiz_main_template", url: "/UserControls/Quiz/Quiz_Main.tmpl.htm" },
        { target: "#quiz_media_left_template", url: "/UserControls/Quiz/Quiz_Media_Left.tmpl.htm" },
        { target: "#quiz_media_right_template", url: "/UserControls/Quiz/Quiz_Media_Right.tmpl.htm" },
        { target: "#quiz_no_media_template", url: "/UserControls/Quiz/Quiz_No_Media.tmpl.htm" }]

    function loadTemplates(templates, callback) {
        if (templates.length) {
            var nextTemplate = templates.pop();
            $(nextTemplate.target).load(nextTemplate.url, loadTemplates(templates, callback));
        } else {
            callback.call();
        }
    }

    function init() {
        loadTemplates(_templates, function () { alert("Done!");})
    }

    return {
        init: init
    };
})(jQuery);

$(function () {
    App.Quiz.init();
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!