2012-06-11 76 views
4

免責聲明 - 我不完全確定這甚至是可能的。但在那種情況下,我仍然希望有人指出某種可能的替代方案或黑客行爲。jQuery可排序 - 基於輸入字段值的排序

這是情況。

我有一個工作列表,它使用jQuery UI排序,因此用戶可以拖放列表上的項目。

jQuery的:

$(document).ready(function() { 
    $("#test-list").sortable({ 
     handle : '.big-handle', 
     update : function() { 
      var order = $('#test-list').sortable('serialize'); 
     $("#info").load("../sortable/process-sortable.php?"+order); 
     } 
    }); 
}); 

阿賈克斯部分存儲新秩序在數據庫中,你不需要擔心。

的HTML:

<ul id="test-list"> 
<li id='listItem_1'><div class='main-item big-handle'><img src='../sortable/arrow.png' alt='move' width='16' height='16' class='handle' /><strong>Item 1</strong></div></li> 
<li id='listItem_2'><div class='main-item big-handle'><img src='../sortable/arrow.png' alt='move' width='16' height='16' class='handle' /><strong>Item 1</strong></div></li> 
<li id='listItem_3'><div class='main-item big-handle'><img src='../sortable/arrow.png' alt='move' width='16' height='16' class='handle' /><strong>Item 1</strong></div></li> 
</ul> 

這一切工作正常。現在,棘手的部分。我的客戶希望在用戶可以輸入數字的每個列表項旁邊都有一個輸入字段,它應該將該列表項移動到指定的位置。因此,如果用戶輸入「1」到列表項目號旁邊的字段中。 3,那麼該項目應該移動到列表中的第一個位置,就像它被拖到那裏一樣。這可以做到嗎?

不需要你爲整個列表提出一個完整的解決方案,假設我只需要一個可以移動項目編號的字段。 3左右。

回答

0

試試這個

​$('input').on('blur', function(){ 
    var $el = $(this), 
    pos = $el.val(), 
    $parent = $el.closest('li'); 

    $parent.insertBefore($('li').eq(pos)); 

})​​​ 

的功能演示:http://jsfiddle.net/YyvjH/

的過渡效果,以模擬阻力可能在CSS3來完成。

+0

可能想修復小提琴鏈接。 – j08691

+0

Thx j08691 !! :) –

0

eq(2)方法獲得我們刪除的第n個匹配元素。在這種情況下,從 位置3(索引2),因爲這是你要求移動的那個。我們將它從DOM 中刪除,然後將其插入到輸入框中指定的位置。

//do this on blur 
var index = parseInt($("input").val()) 
    , element = $("#test-list li").eq(2).remove(); 
$("#test-list li").eq(index - 1).before(element); // -1 because users like 1 based indices 
+0

使用該代碼時出現'非法字符'錯誤。 – jovan

1

如何:jsFiddle example

$("#test-list").sortable({ 
    handle: '.big-handle', 
    update: function() { 
     var order = $('#test-list').sortable('serialize'); 
     $("#info").load("../sortable/process-sortable.php?" + order); 
    } 
}); 

$("#test-list input").blur(function() { 
    var pos = $(this).val() - 1; 
    if (pos >= 0 && pos <= $("#test-list li").length - 1) { 
     if ($(this).parents('li').index() > pos) { 
      //move up 
      $(this).parents('li').insertBefore($("#test-list li:eq(" + pos + ")")); 
     } 
     if ($(this).parents('li').index() < pos) { 
      //move down 
      $(this).parents('li').insertAfter($("#test-list li:eq(" + pos + ")")); 
     } 
     $("#test-list input").val(''); 
    } 
});​