我正在尝试使用 ajax 加载一些内容,然后用新下载的内容替换页面上的现有内容。问题是我需要为替换数据绑定(bind) load(handler(eventObject))
事件。我需要在加载所有图像时触发它。这是我目前所拥有的:
$("#mainContentHolder").live("load", function(){
alert("images loaded!")
});
$.get("content.htm", function(data){
$("#mainContentHolder").replaceWith(data);
alert("content is loaded!");
});
我在加载内容时看到一个警报,但它发生在图像加载之前并且图像加载警报永远不会发生(我还尝试了 bind()
而不是 live()
之前)。
有人知道解决办法吗?
最佳答案
这可能是也可能不是你的问题,但看起来你附加图像加载函数的容器在你加载 ajax 内容时被替换了:
$("#mainContentHolder").live("load", function(){ //you are attaching to current and future '#mainContentHolder' elements
alert("images loaded!")
});
$.get("content.htm", function(data){
$("#mainContentHolder").replaceWith(data); //'#mainContentHolder' element is replaced with something else
alert("content is loaded!");
});
不确定从您的 AJAX 调用返回的内容是什么,但如果它没有 #mainContentHolder
元素,则您的图像加载事件处理程序将无法附加任何内容。
如果不是这样,还有这个:(来自 http://api.jquery.com/load-event/ )
It is possible that the load event will not be triggered if the image is loaded from the browser cache. To account for this possibility, we can use a special load event that fires immediately if the image is ready. event.special.load is currently available as a plugin.
希望其中之一能帮助您。
关于javascript - replaceWith 后的 jQuery 加载事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4372251/