每次图像加载完成时运行一个函数
我想知道如何使用 JQuery 创建一个函数,该函数将在每次图像加载完成时运行。我希望该函数每次都被调用,而不仅仅是一次。因此,例如,如果我有“image1.jpg”并且它是在页面开始时加载的,则将调用该函数。然后,如果我更改图像并且在使用 Javascript 更改图像后再次加载它,我希望再次触发“已加载”函数。我尝试了 Jquery Load() 函数,但它只运行一次,而不是在图像被替换为另一个图像后运行第二次。
我还希望即使图像也被缓存,事件也会发生。这意味着每次我更改图像的“src”属性时,我都希望再次启动特定的函数,即使图像已经被缓存。
示例:
$("#myimageselector").attr("src", "http://domain.com/the_new_image.jpg");
我希望当发生这种情况时,即使图像已经缓存,该函数也会触发。我认为有可能知道图像是否已被缓存。我只需要一个 .load() 函数,它会运行一次(当然),如果它没有被执行,则意味着图像已被缓存。至少对于我的具体用途来说。
想法:也许我们应该绑定一个事件来检查 DOM 中特定元素更改的变化。因此,如果图像已完成加载,则特定的 DOM 元素可能会发生更改,因此我们可以检查之前和之后的值。
谢谢。
I wanted to know how to use JQuery to create a function that will run on each time an image has been finished loading. I want that function to be called EACH TIME, not only once. So if, for example, I have "image1.jpg" and it was loaded on page start, the function will be called. Then, if I change the image and it was loaded again after I changed it using Javascript, I want that 'loaded' function to fire again. I tried Jquery Load() function, but it only run once, not the second time after the image has been replaced with another one.
I want also that the even will happen even if the image has been cached too. That means that every time I change thew 'src' attribute of the image, I want that a specific function to fire up - again, even if the image is already been cached.
Example:
$("#myimageselector").attr("src", "http://domain.com/the_new_image.jpg");
I want that when this happens, even if the image is already cached the function will fire. I think that it's possible to know if the images has been cached, kind of. I just need to have an .load() function that will run once (of course), and if it hasn't been executed, it means that the image has been cached. At least for my specific usage.
Thought: maybe we should bind an event that checked a change in the DOM for a specific element change. So maybe if the image has been finished loading, a specific DOM element is changed, so we can check the before and after values.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我最接近您想要的解决方案,还可以处理缓存的图像。
我创建了一个 jQuery 插件:
用法:
背后的概念:
load
和error
事件处理程序load
或error
事件。触发后,轮询器被清除,并执行传递的函数。The closest I get to your desired solution, to also deal with cached images.
I've created a jQuery plugin:
Usage:
The concept behind this:
load
anderror
event handlersload
orerror
event will be triggered. Upon triggering, the poller is cleared, and the passed function is executed.您可以对 Img 标签使用 onLoad 函数
you can use the onLoad function for the Img tag
使用 jquery live 方法来跟踪负载。
Use jquery live method to track load.
无论图像是否被缓存,这都会运行:
严格来说,您不需要使用
call()
,但这将允许您以更 jquery 的方式使用有问题的图像元素。 imgLoadFunc 内部:This will run whether image is cached or not:
Strictly speaking, you don't need to use
call()
, but this will allow you to use the image element in question in a more jquery-ish way. InsideimgLoadFunc
: