开发者

How to run action on jQuery selected elements in certain order?

I have a HTML table like this:

<table>
 <tr><td>X</td><td>X</td><td class='latest order1'>X</td><td class='latest order4'>X</td></tr>
 <tr><td>X</td><td>X</td><td class='latest order3'>开发者_运维知识库;X</td><td class='latest order2'>X</td></tr>
 <tr><td>X</td><td>X</td><td class='latest order6'>X</td><td class='latest order5'>X</td></tr>
</table>

Now, I want to run a jQuery action (an ajax call) on all objects of latest class, that's a simple:

$('.latest').each(do_call());

But since the ajax action takes some time, I have the elements ordered by their importance. And I would like to run the do_call() for object with order1, then for order2 element, and so on.

How can I sort jQuery objects, so the actions would run in proper order?


First, get all the .latest elements and their order classes in an array:

var order = [];

$('.latest').each(function() {
    // Get the order - all elements have class 'latest orderX':
    // remove the 'latest', get the classname, and add the latest back.
    order.push($(this).removeClass('latest').attr('class'));
    $(this).addClass('latest');
});

Then sort the array and loop through it, get the corresponding element:

order.sort();

for(var i in order) {
    var obj = $('.latest.'+order[i]);
    do_call(obj);
}

This method works even if your .latest elements are not sequentially indexed; eg. you can have order4 after order1 with no order2 or order3 present and it still works.


this can probably be more efficient but it should do what you are looking for:

var latestItems = $('.latest');
var order = 1;
for(var i = -1, len = latestItems.length; ++i < len ) {
    var item = $('.latest .order' + order);
    doCall.call(item);
    order++;
}


Why not do it all in one 'big' ajax call instead of running separate ajax calls for each element? Figure out a way to consolidate your data in such a way that it be separated on the server side and a have a single response update the elements on the client.


I think you can find AJAX QUEUE plugin usefull. From the manual:

Ajax Queue is a plugin that helps to manage Ajax race conditions. When multiple Ajax requests are made in rapid succession, the results can be returned out of order. This can cause weird behavior in your application. Ajax Queue is a plugin (actually, 2 plugins) that provide a way to manage these requests.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜