2012-03-16 71 views
0

我已經找遍了這個,但沒有太多的運氣。如預期jQuery行更改和ID

$("span[id*=Section]").click(function(){ 
    var row = $(this).parents("tr.MoveableRow:first"); 
    if ($(this).is(".up_button")) { 
     row.insertBefore(row.prev()); 
     section = this.id; 
     $("input[name='" + section + "']").val(row.closest("tr").prevAll("tr").length + 1); 
    } else { 
     row.insertAfter(row.next()); 
     section = this.id; 
     $("input[name='" + section + "']").val(row.closest("tr").prevAll("tr").length + 1); 
    } 
}); 

目前,上/下按鈕點擊時,在TR上移或下移:

所以給這個代碼。 「輸入[名稱=」部分採用傳入的跨度ID值並將新值分配給該TR內的隱藏字段。

這樣做雖然給我重複的ID。因此,例如,我將第2行移動到第1行。舊行2的隱藏輸入值變爲1,但原始1的隱藏輸入也爲1.

所以我需要做的就是讓舊的1,新的2.

+0

你能在[JS小提琴](http://jsfiddle.net/)上重現這個嗎? – 2012-03-16 22:20:29

+0

您似乎不會更改其他行的值。我錯過了什麼嗎? – 2012-03-16 22:21:53

回答

0

難道你不只是爲你移動的行做同樣的事情? (因爲你是在向上和向下的情況下做同樣的事情,你可以簡化你的代碼位)

$("span[id*=Section]").click(function(){ 
    var row = $(this).parents("tr.MoveableRow:first"); 
    if ($(this).is(".up_button")) { 
     row.insertBefore(row.prev()); 
    } else { 
     row.insertAfter(row.next()); 
    } 

    $("input[name='" + this.id + "']").val(row.closest("tr").prevAll("tr").length + 1); 
    $("input[name='" + row[0].id + "']").val(row.closest("tr").prevAll("tr").length + 1); 
}); 

您也可能會使用.index(),但我不知道你的HTML是什麼樣子:

$("span[id*=Section]").click(function(){ 
    var row = $(this).parents("tr.MoveableRow:first"); 
    var offset = 1; // Offset of TR being swapped with (up/down) 

    if ($(this).is(".up_button")) { 
     row.insertBefore(row.prev()); 
    } else { 
     row.insertAfter(row.next()); 
     offset = -1; 
    } 

    var position = $('tr.MoveableRow').index(row) + 1; 
    $("input[name='" + this.id + "']").val(position); 
    $("input[name='" + row[0].id + "']").val(position + offset); 
}); 
+0

爲我做了這份工作,謝謝! – MrCornfed 2012-03-19 21:19:34