javascript - 动态添加图像的加载事件未触发
问题描述
动态添加到#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/ 有什么方法可以检测动态元素的加载事件?
解决方案
您根本没有向图像添加事件,因为您$('#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);
});
推荐阅读
- matlab - 如何在 Matlab 中定义和访问静态属性作为顶级成员?
- laravel - Laravel + Vue/axios Api 调用子域 access-control-allow-origin
- spring-boot - 在请求目标中找到无效字符时如何在springboot中自定义错误消息
- haskell - Haskell - 在不实际使用函数的情况下编码“最大”[初学者]
- kubernetes - 是否可以将整数锚转换或转换为 yaml 文件中的字符串别名?
- javascript - Javascript 书签:编码的 URI
- html - 缩放具有多个宽度和高度约束的图像
- javascript - 无法在三个 js 中旋转或平移我的全景图
- javascript - 在 Iframe 中加载 XSLTProcessor::transformToDocument() 的输出时未执行 Javascript
- javascript - 为什么 emscripten 似乎此代码存在内存泄漏