简体   繁体   中英

jQuery - change table cells position

how can I change via jquery the cells position from 1 2 to 2 1 ?

<table id='mytable'>
   <tr>
       <td>1</td>
       <td>2</td>
   </tr>
</table>
$('#mytable tr td:eq(0)').appendTo('#mytable tr');

JSFIDDLE

If you want to change all the second td to first position in your table, then you can use:

$.each($('#mytable tr td:eq(1)'), function() {
     $(this).insertBefore($(this).prev());
})


Actually, above code will not work if your table have more than one <tr> element, if that is the case then you need to use .find() :

$('#mytable tr').find('td:eq(1)').each(function() {
    $(this).insertBefore($(this).prev());
});

Fiddle Demo

References: .each() , .find() , .insertBefore() , .prev()

with append

http://jsfiddle.net/F7HmQ/1/

$(function(){
   var td = $("td").first() ;
    $("tr").first().append(td);    
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM