2013-05-07 54 views
0

我將新的表單元素添加到可排序列表中。當列表重新排列時,我會將相似的ID連續。到目前爲止的代碼:jquery sortable - 在變更時重新分配連續元素ID

$("#sortable").sortable(); 
$("#sortable").disableSelection(); 

var counter = 1; 

    $('a').click(function() { 
    var elems = '<li>' 
    '<input name="q_' + counter + '" type="text"/>' + 
    '<select name="type_' + counter + '" > 
      <option value="1">1</option> 
      <option value="2">2</option> 
      <option value="3">3</option> 
    </select>' + 
    '</li>' ; 
    $('#sortable').append(elems);  


    counter++;  
    return false; 


}); 

這產生一個帶連續ID的列表,當重新排列時它會不同步。我如何使用jquery遍歷列表並重新分配元素ID?

回答

2

把功能update回調

$("#sortable").sortable({ 
    update: function(event, ui) { 
     $('select').each(function(index){ 
     $(this).attr('id', index + 1); 
     }); 
    } 
}); 
+0

我只想澄清:'change'更新的ID,而你的排序(可能導致的開銷,如果你不需要它)當您鬆開結束排序 – 2013-05-07 13:01:12

+0

這鼠標鍵'update'將更新的ID效果很好。 (函數(索引){(this).attr('name','t_'+ index); }); – 2013-05-07 13:16:02

+0

'+ 1'是多餘的 - 創建01,11,21,31等。 – 2013-05-07 13:17:21

1

內可以使用change事件這一點。

$("#sortable").sortable({ 
    change: function(event, ui) { 
     // reset all the IDs 
     $.each($('select'), function(i, v) { 
     this.id = "type_" + i; // or the "name" attribute? 
     }); 
    } 
});