如何将 jquery 事件绑定到动态添加的多个 DOM 元素



图像供参考1 图像用于参考2我正在按钮click上动态创建多个 DOM 元素。

我正在使用 jquery .on()方法将"图像裁剪插件"绑定到动态添加的 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
  });
});

最新更新