2013-10-02 32 views
0

考慮以下對列表:在一個jQuery排序連接到一個可拖動的列表,我怎麼能告訴特定的列表項目,可拖動項目被放到?

user's queue 
<ul id='list1'> 
    <li>Some</li> 
    <li>Thing</li> 
</ul>eligible items 
<ul id='list2'> 
    <li>Red</li> 
    <li>Green</li> 
    <li>Blue</li> 
    <li>Electric Banana</li> 
    <li>Flamingo Pink</li> 
</ul> 

<script> 
jQuery(function($) { 
    $('#list2 li').draggable({ 
     cursor: 'move', 
     helper: 'clone', 
     connectToSortable: "#list1", 
     update: function(event, ui){ 
      // In here, I can get the item being dragged by inspecting 
      // event.toElement (and probably other ways as well), and 
      // I can find the list I am dropping onto by inspecting 
      // event.target. 

      // But, how do I tell what particular list item in the "user's 
      // queue" (#list1) list that the item is being dropped onto? 
      // E.g., if I drop "Green" onto "Thing", so it displaces "Thing", 
      // and the list now contains "Some, Green, Thing", how can I tell 
      // here in code that "Green" was dropped onto "Thing"? 
     } 
    }); 
    $('#list1').sortable({ 
     revert: true, 
    }); 
}); 
</script> 

Here is a fiddle with that code.

在代碼中的註釋概述了我的問題。重複一遍,我想知道如何以編程方式確定可拖動元素被放到的特定列表項目?

+0

什麼更新方法?被丟棄後你想放? – PSL

+0

我想要做的是發送一個AJAX請求到我的後端,說列表項被插入之前(某個項目)。在實際應用程序中,這是一個具有特定順序的項目隊列,用戶可以將新項目「插入」到列表中。我需要用插入來更新後端。 – Josh

回答

1

如果你的意思是排序的更新,那麼你可以這樣做:

$('#list1').sortable({ 
     revert: true, 
     update: function(event, ui){ 
      ui.item.prev().css('color', 'green'); //get the prev element of item sorted just now, applies for the dropped as well 
      ui.item.next().css('color', 'blue');//get the next element of item sorted just now, applies for the dropped as well 
     } 
    }); 

像這樣的事情?

$('#list1').sortable({ 
     revert: true, 
     update: function(event, ui){ 
      $('.next, .prev').removeClass('next prev'); 

      var $prevElem = ui.item.prev(), 
       $nextElem = ui.item.next(); 
      $prevElem.addClass('prev'); 
      $nextElem.addClass('next'); 
      console.log('Item sorted is before ' + $prevElem.text() + ' after ' + $nextElem.text()); 
     } 
    }); 

Demo

+1

這是一個「更好的方式」+1 – Sergio

+1

這很容易,只是知道如何去做它......當我編寫我的問題時,我非常緊張地確定了「放下目標」的想法,我沒有想過簡單地檢查ui.item上的下一個或上一個元素。在我發佈我的問題並回來討論它之後,我實際上也有過同樣的想法;你的發帖給我一些心理驗證,證明我在正確的軌道上。謝謝! – Josh

相關問題