jquery .each() .load() wait for completion

匿名 (未验证) 提交于 2019-12-03 02:34:02

问题:

I'm loading rows into a table using jquery and I want to know how I can make them load one by one; i.e. the second block should only start to load once the first has finished loading.

My table looks a bit like this:

<table id="dynamicTable">   <thead>     <tr>       <th>Heading</th>       ...     </tr>   </thead>   <tbody id="1">   </tbody>   <tbody id="2">   </tbody> </table> 

And my jquery looks a bit like this:

$("table#dynamicTable tbody").each(function() {   $(this).load("filethatgeneratestablerows.php"); }); 

(it's a little more complicated than this as it generates content based on the tbody id and also includes a checkbox system to choose which tbody elements you want to affect, but that all works fine and so I've stripped it down to make my actual question more obvious!)

回答1:

var bodies = $("table#dynamicTable tbody"),     i = 0;  (function loadBody() {    bodies.eq(i++).load("filethatgeneratestablerows.php", loadBody); })(); 

This calls load on each index of the collection one at a time. When one load is done, it calls loadBody again, using the incremented index.

When i is greater than the last one, .eq() will return an empty jQuery object, so the sequence will end there.



回答2:

You'll need to make an array to store the various tbodies. Start with the first and run a load. On complete pass the array with the first taken out. So you pass around like so:

[1, 2, 3, 4] [2, 3, 4] [3, 4] [4] []

And you keep calling a load function that takes in an array, loads the first element, and passes the remaining elements or breaks on none.

EX:

loadElement( $("table#dynamicTable tbody") );  function loadElement( $elements ) {     $elements.load( "filethatgeneratestablerows.php",             loadElement( $elements.filter(":gt(0)") ) ); } 


回答3:

You could do a

$("table#dynamicTable #1").load("filethatgeneratestablerows.php", function(event) {      $("table#dynamicTable #2").load("filethatgeneratestablerows.php", function(event) {         ....      });   }); }); 

not tested but you should get the point



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