将jQueryUI Resizable小部件应用于动态创建的元素
这个问题与事件授权无关
我想将jQuery可resize的小部件应用于一系列可能动态创建的div
标签。
有没有办法使用行为类似于事件委托的东西来动态地将jQuery resizable
小部件添加到新元素?
这是示例(请注意新创建的绿色元素无法resize):
$(function() { var cols = $("#cols").children(".col"); cols.resizable({ maxHeight: 20, minHeight: 20, distance: 5, handles: 'e', start: function() { console.log("I've started!"); }, stop: function() { console.log("I've stopped!"); } }); $("#addNew").on("click", function() { cols.filter(":last").after('' + parseInt(cols.length + 1) + ''); cols = $("#cols").children(".col"); }); });
.col { float: left; width: 20px; height: 20px; background: #f00; margin-right: 1px; } .col.new { background: #0f0; } button { clear: left; display: block; margin-top: 10px; }
1 2 3 4
编辑:我不是在询问事件委托 ,我问是否有办法委托可resize的小部件来动态地将它添加到新创建的元素。
你需要重新初始化col.resizable();
一旦新元素添加。 请查看以下工作代码:
$(function() { var cols = $(".col"); cols.resizable({ maxHeight: 20, minHeight: 20, distance: 5, handles: 'e', start: function() { console.log("I've started!"); }, stop: function() { console.log("I've stopped!"); } }); $("#addNew").on("click", function() { cols.filter(":last").after('' + parseInt(cols.length + 1) + ''); cols = $(".col"); cols.resizable({maxHeight: 20, minHeight: 20, distance: 5, handles: 'e'}); }); });
.col { float: left; width: 20px; height: 20px; background: #f00; margin-right: 1px; } .col.new { background: #0f0; } button { clear: left; display: block; margin-top: 10px; }
1 2 3 4
我知道这是一个老post,但我觉得我可以发布一个更好的答案以供将来参考。因为在你的评论中你提到过代码重用而不是多次将插件应用于元素,这个解决方案应该克服这些问题。
$(function() { ApplyResizablePluginToCol($(".col")); // cal the function by passing all the elements to which the plugin must be applied to $("#addNew").on("click", function() { $(".col:last").after('' + parseInt( $(".col").length + 1) + ''); ApplyResizablePluginToCol($(".col:last"));// take the last element, ie the element that is created just now }); function ApplyResizablePluginToCol(elements){ //reusable function elements.resizable({ maxHeight: 20, minHeight: 20, distance: 5, handles: 'e', start: function() { console.log("I've started!"); }, stop: function() { console.log("I've stopped!"); } }); } });
.col { float: left; width: 20px; height: 20px; background: #f00; margin-right: 1px; } .col.new { background: #0f0; } button { clear: left; display: block; margin-top: 10px; }
1 2 3 4
试试这个代码它对我有用
$("#cols").on('mouseenter',cols,function(){ cols.resizable({ maxHeight: 20, minHeight: 20, distance: 5, handles: 'e', start: function() { console.log("I've started!"); }, stop: function() { console.log("I've stopped!"); } }); });