2010-12-21 70 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 方法重复你的实现。