JQuery chaining .load () queries?

So now I have been working with jQuery . load () , and it looks like we cannot configure $("#example").load('./uri.ext #ID')to chain like for example:

$("#example").load('./uri.ext #ID1').load('./uri.ext #ID2').load('./uri.ext #ID3')

Which, of course, would be useful if we had a DIV template file or something to dynamically build the page, and not store HTML in a string variable or something like that ... plus, we could save some of them into one file.

Ideally, I would like to somehow enclose such things with this command:

<div id="example">
    <div id="ID1">
        <div id="ID2">
            <div id="ID3">
            </div>
        </div>
    </div>
</div>

The problems that I get are doubled. Firstly, the async : truerequest property causes the next request to be launched, and the allocation is not transformed as intended. Then I tried to run the nested $ ("# example"). Load ('./uri.ext # ID1'). AjaxCompletes (function () {/next.load () in the sequence /}) `, which ended up in a recursive trap that did not end and continued to send requests for these files.

Any thoughts on how to accomplish what I need with the syntax / method I tried? Also, if this is not a problem and just a misunderstanding in my part of the jQuery chain, the explanation I would really appreciate any explanation for this.

+3
source share
2 answers

, :

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

EDIT ES6:

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

.

, , . , . , .

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();
});
0

Source: https://habr.com/ru/post/1765298/


All Articles