【问题标题】:Load event for dynamically added images are not firing [duplicate]动态添加图像的加载事件未触发[重复]
【发布时间】:2019-08-28 03:56:07
【问题描述】:

动态添加到 #div 的图像的加载事件不起作用,而单击/鼠标悬停等其他事件则正常。

<div id="test">
  <img src="https://via.placeholder.com/50" />
</div>

js

$(document).ready(function() {
    // does not work
    $('#test').on('load', 'img', function() {
    alert('loaded');
  });

  // work fine
  $('#test').on('click', 'img', function() {
    alert('clicked');
  });
  setTimeout(() => {
    $('#test').append('<img src="https://via.placeholder.com/150" />');
  }, 1000);
  setTimeout(() => {
    $('#test').append('<img src="https://via.placeholder.com/250" />');
  }, 2000);
  setTimeout(() => {
    $('#test').append('<img src="https://via.placeholder.com/350" />');
  }, 3000);
});

检查小提琴:https://jsfiddle.net/zkpt2crg/ 有什么方法可以检测动态元素的加载事件?

【问题讨论】:

  • 与大多数 jQuery 事件不同,图像上的load 不会冒泡,这是为委托事件提供的。
  • 实现您的 sn-p 的链接答案:jsfiddle.net/x941gv3f

标签: javascript


【解决方案1】:

您只是没有向图像添加事件,因为您的 $('#test').on('load', 'img') 还没有看到任何图像

演示https://jsfiddle.net/710Ln2sa/

您应该明确地将事件附加到图像

$(document).ready(function() {
  // extract to reusable function
  function onload () {
    alert('loaded');
  }
  setTimeout(() => {

    // create image
    const $img = $('<img src="https://via.placeholder.com/150" />')

    // attach load event
    $img.on('load', onload)

    $('#test').append($img);
  }, 1000);
});

【讨论】:

  • on() 方法为现在和将来存在的元素附加了事件行为——这就是click 事件起作用的原因。问题是,为什么这同样不适用于load 事件?
  • 你确定attaches event to elements in the future? Docs 没有这样说
  • 看看这个:jqueryhouse.com/…
  • 另外,查看点击事件绑定到 OP 中图像的方式 - 尝试点击所有图像
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-04
  • 2020-06-01
  • 2023-04-08
  • 1970-01-01
相关资源
最近更新 更多