2009-12-04 103 views

回答

0

HTML

<table id="t1"> 
    <tr> 
     <td>abc</td> 
    </tr> 
    <tr> 
     <td>efg</td> 
    </tr> 
</table> 

使用Javascript(jQuery的)

var row0 = $('#t1 tr:eq(0)'); 
$('#t1 tr:eq(1)').after(row0.contents()); 
row0.remove(); 
-1

我會分配ID給我所有的<tr>秒。

6

這是我爲你寫的一個快速插件。 在桌子上調用它,並將舊的行和新的行位置給它。

$.fn.extend({ 
    moveRow: function(oldPosition, newPosition) { 
    return this.each(function(){ 
     var row = $(this).find('tr').eq(oldPosition).remove(); 
     $(this).find('tr').eq(newPosition).before(row); 
    }); 
    } 
}); 

$('#myTable').moveRow(4, 3); 

這裏有jsbin一個例子:http://jsbin.com/uroyi

+0

+1 - 非常簡潔的答案。如果''有事件處理程序綁定到它,這個插件會保留它們嗎? – 2009-12-04 08:57:45

+0

對不起,但它不會。根據jQuery文檔,您需要直接執行appendTo以保留事件處理程序。 http://docs.jquery.com/Manipulation/remove#expr – bang 2009-12-04 09:18:46

+2

我刪除了上面的評論,因爲我錯了,這裏是我仍然支持的信息。謝謝你,讓我出去。 事件不會被保存。我建議使用$ .live(),因爲對於超過3行以上的版本,這會更有效率。在直播的情況下,這些事件不會直接附加到元素上,所以它會使用不太友好的插件。 – 2009-12-04 09:21:11

1

這裏有兩個JavaScript函數,將做的工作:

function MoveRowDown(tableId, index) 
    { 
     var rows = $("#" + tableId + " tr"); 

     rows.eq(index).insertAfter(rows.eq(index + 1)); 
    } 

    function MoveRowUp(tableId, index) 
    {   
     var rows = $("#" + tableId + " tr"); 

     rows.eq(index).insertBefore(rows.eq(index - 1)); 
    } 
4

Alex的答案的偉大工程,卻發現一個問題,如果你移動的東西到列表的最後,它不能插入它。下面是修復它稍微調整了版本...

$.fn.extend({ 
    moveRow: function (oldPosition, newPosition) { 
     return this.each(function() { 
      var row = $(this).find('tr').eq(oldPosition).detach(); 
      if (newPosition == $(this).find('tr').length) { 
       $(this).find('tr').eq(newPosition - 1).after(row); 
      } 
      else { 
       $(this).find('tr').eq(newPosition).before(row); 
      } 
     }); 
    } 
}); 
+0

感謝兄弟!現在效果很好 – 2013-08-23 13:31:09

0

如果你想將它移動到頂部或底部會更容易些,雖然這不會幫助你:(

//lets say you want to avoid/skip table headers and use a tbody 
var tbody = $('tbody','#table'); 
//now you want a specific row bring to top 
$('tr.chieftan',tbody).prependTo(tbody); 

要移動從具體指標,到特定的一個:

$('li:eq(2)').insertBefore($('li:eq(1)')); 

將第二前移動第三子(該指數法是基於0)

相關問題