image for reference1 images for reference2我在按钮 click
上动态创建多个 DOM 元素。
我使用 jquery .on()
方法将“图像裁剪插件”绑定(bind)到动态添加的 DOM 元素,但它仅适用于第一个 DOM 元素,不适用于第二个、第三个。
单击第一个 DOM 时,将打开对话框以选择图像,但不会打开第二个 DOM 元素,如图所示。
$("#add-button").on('click', function() {
$('#gallery-div').append('<div class="col-md-4"><a href="javascript:void(0);" class="gallery-remove">×</a><label class="upload_testi remove"><span>Choose file</span><input id="gallery-img" class="crop-dynamic-cls" type="hidden" name="test[image]"></label></div>');
$(document).on("click", "a.gallery-remove", function() {
$(this).parent().remove();
});
$(document).on('click', '#gallery-div', function() {
$(this).find('label').each(function() {
$('.crop-dynamic-cls').awesomeCropper({
width: 1020,
height: 434,
debug: true
});
})
})
})
最佳答案
尝试这样的操作,还要检查我是否已将选择器更改为 .gallery-remove,而不是 a.gallery-remove
$(document).ready(function() {
// first register your handler for all future added elements to the DOM
$(document).on("click", ".gallery-remove", function() {
console.log('remove the parent');
});
// Then register the handler that will add stuff to the DOM
$("#add-button").on('click', function() {
$('#gallery-div').append('<div class="col-md-4"><a href="javascript:void(0);" class="gallery-remove">×</a><label class="upload_testi remove"><span>Choose file</span><input id="gallery-img' + i + '" class="crop-dynamic-cls" type="hidden" name="test[image]"></label></div>');
// do other stuff here
});
});
关于jquery - 如何绑定(bind)jquery事件动态添加多个DOM元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56575979/