jquery - 如何绑定(bind)jquery事件动态添加多个DOM元素?

标签 jquery

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">&times;</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">&times;</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/

相关文章:

jquery - bootstrap 是否支持列宽等于零以便在超小屏幕中隐藏网格列?

javascript - 我想将日期格式更改为 "yyyy-mm-dd"

jquery - 在单击事件或鼠标按下事件上切换输入类型单选

javascript - jQuery 在点击时调用自定义函数

javascript - 如何使用 javaScript 和 jQuery 从 URL 保存 json 对象

javascript - Internet Explorer 8 的 JQuery/CSS 不显示背景图像

jquery - 使用 jQuery 生成不同结果的复选框组合

javascript - 在第一个子 <div> 之后使用 <div> 标签包装内容

javascript - 让 jquery 插件在 Ajax 调用后工作

jquery - 使用 Google Analytics 和多个域跟踪预订