POST请求更新div内容后如何恢复元素的jQuery draggable可拖拽属性
动态插入元素丢失draggable属性的解决方法
核心原因
页面初始化阶段执行的$(".GroupContentRow").draggable()绑定逻辑,仅会作用于当时DOM中已经存在的.GroupContentRow元素。后续通过.html()方法动态插入的新列表项,没有经过draggable初始化,自然不会继承拖拽属性。
解决步骤
1. 封装可拖拽元素的初始化逻辑
把原有draggable绑定代码抽成独立的可复用函数,避免重复编写配置:
function initDraggableRows() { $(".GroupContentRow").draggable({ appendTo: "body", cursor: "move", helper: 'clone', revert: "invalid" }); }
2. 页面初始化时调用一次函数
替换原有draggable绑定代码为函数调用,保证初始加载的列表项可以正常拖拽:
$(function() { // 原有容器尺寸初始化逻辑不变 $(".MemberList2").height($(window).height() - 20); var dropSpace = $(window).width() - $(".MemberList2").width(); $("#dropZone").width(dropSpace - 70); $("#dropZone").height($(".MemberList2").height()); // 调用封装好的拖拽初始化函数 initDraggableRows(); // droppable绑定逻辑无需修改,因为绑定对象是未被替换的容器元素,不需要重复初始化 $(".GroupContentMemberList").droppable({ tolerance: "intersect", accept: ".GroupContentRow", activeClass: "ui-state-default", hoverClass: "ui-state-hover", drop: function(event, ui) { $(".GroupContentMemberList").append($(ui.draggable)); $.post("index.php", { save: "yes", id: $(ui.draggable).attr('id'), saveIn: 0 }) .done(function(data) { console.log("Data Loaded: " + data); }); } }); $(".GroupContent").droppable({ tolerance: "intersect", accept: ".GroupContentRow", activeClass: "ui-state-default", hoverClass: "ui-state-hover", drop: function(event, ui) { $(this).append($(ui.draggable)); $.post("index.php", { save: "yes", id: $(ui.draggable).attr('id'), saveIn: $(this).attr('id') }) .done(function(data) { console.log("Data Loaded: " + data); }); } }); })
3. 动态替换内容后重新调用初始化函数
修改搜索接口的回调逻辑,插入新内容后立刻调用封装的函数,给新列表项绑定拖拽属性:
$('#find').on('input', function(e) { console.log("Handler for .change() called."); $.post("index.php", { find: "yes", filter: $('#find').val() }) .done(function(data) { console.log("Data Loaded: " + data); $('.GroupContentMemberList').html(data); // 新增调用:为新插入的列表项绑定draggable initDraggableRows(); }); });
内容的提问来源于stack exchange,提问作者Ivan Rodriguez
相关产品推荐
相关产品推荐

