jQuery .load()回调函数多次触发 [英] jQuery .load() callback function fires multiple times
问题描述
第一次执行代码将正确生成:
加载完成
the first time the code is executed it correctly produces:
load complete
但是第二次产生:
加载完成
加载完成
but the 2nd time it produces:
load complete
load complete
第三次产生:
加载完成
加载完成
加载完成
the 3nd time it produces:
load complete
load complete
load complete
等...因此,第20次load函数完成回调函数时,将触发20次.
etc... so the 20th time the load function completes the call back function gets fired 20 times.
$('#image-tag').load(function () {
console.log("load complete");
});
}).attr('src', 'image.jpg').appendTo('#main');
您知道是什么导致回调函数像这样重复/增加吗?
any idea what's causing the call back function to repeat/increase like this?
推荐答案
这是因为您每次运行该代码时都会添加另一个事件处理程序.
That's because you are adding another event handler every time you run that code.
如果要将图像标签附加到元素中,则不应使用页面中已存在的图像.而是创建一个新的图像标签:
If you want to append an image tag into an element, you should not use an image that already is in the page. Create a new image tag instead:
$('<img/>').load(function () {
console.log("load complete");
}).attr('src', 'image.jpg').appendTo('#main');
这篇关于jQuery .load()回调函数多次触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!