可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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