Move table rows with jQuery
I have this code:
<table>
<tr id="a"><td>A</td></tr>
<tr id="d"><td>D</td></tr>
<tr id="e"><td>E</td></tr>
<tr id="b"><td>B</td></tr>
<tr id="c"><td>C</td></tr>
</table>
How with jQuery can I put the rows in order?
Update: I need to use a move function not a sort functi开发者_JS百科on, since the real id's are not letters. Sorry for the confusion. I want to do something like this:
$("#a").after(rows_b_and_c)
But I don't know how to get the rows.
if you have no events attached to <td>
s and contents are just text, this will do:
var tds = $('table tr').sort(function(a,b){
return $('td:eq(0)',a).text() > $('td:eq(0)',b).text();
});
$('table').html(tds);
jsfiddle demo
that depends... how would you order it? please be more specific.
will to give you a hint, you might wanna check out:
.after() Insert content, specified by the parameter, after each element in the set of matched elements.
.before() Insert content, specified by the parameter, before each element in the set of matched elements.
.insertAfter() Insert every element in the set of matched elements after the target.
.insertBefore() Insert every element in the set of matched elements before the target.
you're funny. :p
you said you know those functions then you did not get to solve the problem.
anyway, here are some of the ways to do it: http://jsfiddle.net/reigel/7Pb6a/1/
Cleaner:
var sortID = function(a,b){
return a.id > b.id ? 1 : -1;
};
$('table tr').sort(sortID).appendTo('table');
精彩评论