Javascript 检查是否加载了动态添加的图像
我正在创建一个简单的html页面,其中一个图像被动态添加到div中,如下所示Javascript 检查是否加载了动态添加的图像,javascript,jquery,html,Javascript,Jquery,Html,我正在创建一个简单的html页面,其中一个图像被动态添加到div中,如下所示 $(".step3html").html('<img class="mobimg thumbnail" src="img/'+keys+'">'); 这里有一个测试小提琴你可以写: $('.mobimg').load(function(){ //your code }); 当所有元素和子元素都被完全加载时,.load()被激发。下面的代码可以工作 $(".step3html").html('<
$(".step3html").html('<img class="mobimg thumbnail" src="img/'+keys+'">');
这里有一个测试小提琴你可以写:
$('.mobimg').load(function(){
//your code
});
当所有元素和子元素都被完全加载时,.load()
被激发。下面的代码可以工作
$(".step3html").html('<img class="mobimg thumbnail" src="https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150">');
$(".mobimg").on('load', function() {
alert("das");
});
$(“.step3html”).html(“”);
$(“.mobimg”).on('load',function(){
警报(“das”);
});
试试这把小提琴
你可能有不同的问题。您是否检查了控制台中键的值
编辑
这是一把小提琴
添加一个事件监听器,让图像通过onload宣布自己
<img class="mobimg thumbnail" onload='loadedImageFunction(this.id)' src="https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150">
然后编写javascript函数
与所有事件一样,在尝试将加载处理程序绑定到图像元素之前,图像元素必须存在。这就是为什么有效但无效
加载处理程序必须在加载映像之前绑定
典型的模式是to。您应该从新创建的元素开始,img
。这个代码有效
<button id="btn">button</button>
<div id="div"></div>
<script type="text/javascript">
$(document).ready(function () {
$('#btn').click(function () {
$('<img class="mobimg thumbnail" src="/images/hat22.jpg?a='
+ Math.random()/*ensure load from server*/ + '" />').load(function () {
console.log('load');
$('#div').empty().width($(this).prop('naturalWidth') + 10).append(this);
});
});
});
</script>
按钮
$(文档).ready(函数(){
$('#btn')。单击(函数(){
$('').load(函数(){
console.log('load');
$('#div').empty().width($(this).prop('naturalWidth')+10).append(this);
});
});
});
啊,sry我没有看到你的编辑。.load()是.on('load',handler)的快捷方式。是的,它不起作用可能是因为图像是动态添加的。我想到的是缓存!因此,可能您的图像已经缓存(例如,如果设置了源,则图像将开始加载)。在这种情况下,您可以尝试将默认的.load()处理程序替换为:。一个(“load”,handler).each(函数(){if(this.complete)$(this.load();});这提供了.load()-handlerNo.的唯一性。即使我加载了新的图像,它也不起作用。我用它点击按钮,请检查它不起作用。看我的答案。代码必须从新元素开始。
<button id="btn">button</button>
<div id="div"></div>
<script type="text/javascript">
$(document).ready(function () {
$('#btn').click(function () {
$('<img class="mobimg thumbnail" src="/images/hat22.jpg?a='
+ Math.random()/*ensure load from server*/ + '" />').load(function () {
console.log('load');
$('#div').empty().width($(this).prop('naturalWidth') + 10).append(this);
});
});
});
</script>