2010-12-21 72 views
3

這是一個可拖動的可排序的例子在jqueryui網站上,我需要使用live()這個(我認爲),因爲元素是通過ajax創建的,是否有人知道如何將活動事件應用到下列?jquery UI可拖動的生活

<script> 
    $(function() { 
     $("#sortable").sortable({ 
      revert: true 
     }); 
     $("#draggable").draggable({ 
      connectToSortable: "#sortable", 
      helper: "clone", 
      revert: "invalid" 
     }); 
     $("ul, li").disableSelection(); 
    }); 
    </script> 
+0

我知道這已經快一歲了,但我發現這對於使新創建的元素可以拖動很有用:http://enterprisejquery.com/2010/07/configuring-ui-widgets-and-interactions-with-live /。 – Will 2011-10-07 13:37:16

回答

2

你不使用live這個(我不認爲你可以),只需勾起來,一旦你加入他們,在success處理。例如,如果使用load

$("#target").load("your url", function() { 
    // Replace the selectors below to match what you load 
    $("#target *[data-name=sortable]").sortable({ 
     revert: true 
    }); 
    $("#target *[data-name=draggable]").draggable({ 
     connectToSortable: "#target *[data-name=sortable]", 
     helper: "clone", 
     revert: "invalid" 
    }); 
    $(this).find("ul, li").disableSelection(); 
}); 

Live Example

使用該修改HTML從jQuery UI演示頁(剛剛更換id值與data-name代替,所以他們不必是唯一的):

<ul> 
    <li data-name='draggable' class="ui-state-highlight">Drag me down</li> 
</ul> 

<ul data-name="sortable"> 
    <li class="ui-state-default">Item 1</li> 
    <li class="ui-state-default">Item 2</li> 
    <li class="ui-state-default">Item 3</li> 
    <li class="ui-state-default">Item 4</li> 
    <li class="ui-state-default">Item 5</li> 
</ul> 
2

我不認爲可以根據需要進行現場活動。最好的選擇是在向列表添加新元素時使用回調函數,並在每次有新元素時將新對象重新啓用爲可拖動狀態。

事情是這樣的:

// Call to add a new element 
$.ajax({ 
    url: 'addElem', 
    success: function(data) { 
    $("#newDraggableObject").draggable({ 
     connectToSortable: "#sortable", 
     helper: "clone", 
     revert: "invalid" 
    }); 
    } 
}); 
2

我有完全相同的問題,我認爲這是一個更好的主意使用一個jQuery插件的方法來解決這個問題:

//Add draggable feature: 
//Define a setup method for the draggable config so we can reuse it for dynamic elements 
$(function() { 
    jQuery.fn.draggableSetup = function draggableSetup() { 
     this.draggable(
     { 
      // enter your custom draggable code here... 
     }); 
     return this; 
    } 
}); 

//Apply the draggable config your dynamic elements after adding them 
$("#dynamic_element_id").draggableSetup(); 

感謝this post獲取答案。

這給你一個可重複使用的解決方案,你不必爲每個ajax 方法重複你的實現。