How do I use jQuery for client-side sorting of div tags?
I want to allow the user of a web app to sort results of a query without a serve开发者_开发问答r call. I'm looking for the usual type of click-the-header-to-sort-based-on-the-column.
However, I'm not working with an actual table. I'll be manipulating div tags based on contents. Is there a jQuery method to facilitate this?
This Tutorial will guide you down the path you seek. It is focused on sorting tabular data in html tables, but you can easily re-purpose the examples to work with a group of divs or list elements, or whatever.
Some of the guidance teaches raw JavaScript techniques, with jQuery peppered in for support, so it's a good guide. For example, it teaches you how to use JavaScript's build in sort()
method. Want to sort alphabetically? Here's a modified snippet from that guide:
var parent_of_divs = $('#parent-of-divs'), rows;
rows = parent_of_divs.children('div').get();
rows.sort(function(a, b) {
var keyA, keyB;
keyA = $(a).text().toUpperCase();
keyB = $(b).text().toUpperCase();
if (keyA < keyB) return -1;
if (keyA > keyB) return 1;
return 0;
});
$.each(rows, function(index, row) {
parent_of_divs.append(row);
});
See this question about sorting li items. With little changes it can also be applied in your case. Among others, the TinySort plug-in is recommended.
There's an ok example here:
Example
I found it to be pretty good. Also, it's a light weight plugin (if you don't want to implement your own). To me, the code was pretty clear even though I am new to the language.
you might want to look into using jquery template lib. you can create a template, and then pass a data object to the template to render. when you want to change the sort order, you would be able to change the data object, and then "update()" your template.
精彩评论