【问题标题】:jquery UI draggable with livejquery UI 可实时拖动
【发布时间】:2010-12-21 08:37:23
【问题描述】:
这是 jqueryui 网站上的一个可拖动的可排序示例,我需要将 live() 与这个(我认为)一起使用,因为元素是通过 ajax 创建的,有人知道如何将实时事件应用于以下内容吗?
<script>
$(function() {
$( "#sortable" ).sortable({
revert: true
});
$( "#draggable" ).draggable({
connectToSortable: "#sortable",
helper: "clone",
revert: "invalid"
});
$( "ul, li" ).disableSelection();
});
</script>
【问题讨论】:
标签:
jquery
draggable
live
【解决方案1】:
我认为不可能按照您的意愿进行现场活动。最好的选择是在将新元素添加到列表时使用回调函数,并在每次有新元素时重新启用新对象可拖动。
类似这样的:
// Call to add a new element
$.ajax({
url: 'addElem',
success: function(data) {
$( "#newDraggableObject" ).draggable({
connectToSortable: "#sortable",
helper: "clone",
revert: "invalid"
});
}
});
【解决方案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
使用 jQuery UI 演示页面中修改后的 HTML(只是将 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>
【解决方案3】:
我遇到了完全相同的问题,我认为使用 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 重复实施
方法。