javascript jQuery 绑定(“加载”)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5807021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery bind("load")
提问by David Horák
var imgLoader = $("<img />");
$(imgLoader).attr("src", "http://localhost/malevil/Content/Images/img_adrenalin.jpg");
$(imgLoader).unbind('load');
$(imgLoader).bind('load', function () {
alert("event fired");
});
But this work only in chrome, where is the problem ? In IE, Firefox and Opera load event never fired.
但这项工作仅在 chrome 中有效,问题出在哪里?在 IE 中,Firefox 和 Opera 加载事件从未被触发。
回答by Pekka
You need to bind the load event before you set the src
property.
您需要在设置src
属性之前绑定加载事件。
As a side note, there are known issues with the load event on images that you need to be aware of:
作为旁注,您需要注意图像上的加载事件存在已知问题:
And, quoting from the jQuery manual on load()
:
并且,从jQuery 手册中 引用:load()
- It doesn't work consistently nor reliably cross-browser
- It doesn't fire correctly in WebKit if the image src is set to the same src as before
- It doesn't correctly bubble up the DOM tree
- Can cease to fire for images that already live in the browser's cache
- 它不能始终如一地工作,也不能可靠地跨浏览器
- 如果图像 src 设置为与以前相同的 src,则它不会在 WebKit 中正确触发
- 它没有正确地冒泡 DOM 树
- 可以停止为已经存在于浏览器缓存中的图像触发
回答by Liv
I would set the handler beforeyou set the src
attribute --as it might be that the image loads before your event handler gets set.
我会在设置src
属性之前设置处理程序——因为图像可能在事件处理程序设置之前加载。