首页 > 解决方案 > 动态添加图像的加载事件未触发

问题描述

动态添加到#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/ 有什么方法可以检测动态元素的加载事件?

标签: javascript

解决方案


您根本没有向图像添加事件,因为您$('#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);
});

推荐阅读