2012-01-05 37 views
13

在一個html表中,我在每一行中都有一個自己的位置編號的單元格。如何在使用jQueryUI排序後正確刷新此位置編號?jQuery ui可排序的表格刷新裏面的數字位置

這是我簡單的HTML:

<table border="0"> 
<thead> 
     <tr> 
     <th scope="col">Position number</th> 
     <th scope="col">Name</th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr> 
     <td>1</td> 
     <td>Text</td> 
     </tr> 
     <tr> 
     <td>2</td> 
     <td>Text</td> 
     </tr> 
    </tbody>   
</table> 

,這是我的js:

var fixHelper = function(e, ui) { ui.children().each(function() { $(this).width($(this).width()); }); return ui; }; 

    $("table tbody").sortable({ 
     helper: fixHelper 
    }).disableSelection(); 

現在,我想正確更改訂單完成排序之後數值的位置。

我該如何做到這一點?

任何幫助,將不勝感激。

回答

22

執行下列排序後..

$("table tbody").sortable({ 
    update: function(event, ui) { 
     $('table tr').each(function() { 
      $(this).children('td:first-child').html($(this).index()) 
     }); 
    }, 
    helper: fixHelper 
}).disableSelection(); 

你可以嘗試(未經測試):的 代替$('table tr').each使用$(this).parents('table').find('tr').each

說明.. 它通過循環每個tr標籤的表內然後更改第一個td-child的內容與索引值tr

+2

非常感謝你,很好的答案和很好的解釋,它完美的作品。 我接受併爲您的答案投了票,如果您願意,您也可以爲我的問題做同樣的事情。非常感謝! – bobighorus 2012-01-05 11:18:39

+2

幫助我 - 很好的迴應和問題 – cantera 2012-04-18 03:01:32

2

如果有人喜歡abo我的答案和我一樣,這裏是Coffeescript

jQuery -> 
    $("ul.sortableEdit").sortable 
      stop: (event, ui) -> 
      $('ul.sortableEdit li').each(-> 
       $(this).children('input.sortableItemPos').val($(this).index()) 
      )