问题描述
我想将jQuery可调整大小的小部件应用于可能可能动态创建的一系列div
标签.
I would like to apply the jQuery resizable widget to a series of div
tags that could potentially be created dynamically.
是否有一种方法可以使用诸如事件委托之类的行为来将jQuery resizable
小部件动态添加到新元素中?
Is there a way to use something that behaves like event delegation to dynamically add the jQuery resizable
widget to new elements?
这是示例(请注意如何无法调整新创建的绿色元素的大小):
Here's the example (notice how the newly created green elements cannot be resized):
$(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('<div class="col new">' + parseInt(cols.length + 1) + '</div>');
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;
}
<link href="https://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<div id="cols">
<div class="col">1</div>
<div class="col">2</div>
<div class="col">3</div>
<div class="col">4</div>
</div>
<button id="addNew">Add</button>
编辑:我不是在问事件委托,而是在问是否有办法委托可调整大小的窗口小部件动态地将其添加到新创建的元素中.
I am not asking about event delegation, I'm asking if there is a way to delegate the resizable widget to dynamically add it to newly created elements.
推荐答案
添加新元素后,您需要重新初始化col.resizable();
.请检查以下工作代码:
You need to reinitialize col.resizable();
once new element added.Please check below working code:
$(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('<div class="col new">' + parseInt(cols.length + 1) + '</div>');
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;
}
<link href="https://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<div id="cols">
<div class="col">1</div>
<div class="col">2</div>
<div class="col">3</div>
<div class="col">4</div>
</div>
<button id="addNew">Add</button>
这篇关于将jQueryUI Resizable窗口小部件应用于动态创建的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!