javascript - replaceWith 后的 jQuery 加载事件

标签 javascript jquery ajax

我正在尝试使用 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/

相关文章:

jquery - Bootstrap 3 Collapse 将我带到页面顶部但也不起作用

javascript - Grails:更改 img src 的 JS 函数没有响应

javascript - 为什么 {} == {} 为假,但 {} + {} == {} + {} 为真

javascript - jquery ajax获取数据并设置为全局变量

javascript - React hooks map 不是一个函数

jquery - css3/html5/jQuery - 股票行情指示器

javascript - HTML 自定义属性在 Jquery 中始终返回未定义

带有字符串的 jQuery .each()

jquery - 悬停在 js 生成的类/元素上不起作用

php - 在 PHP 中使用 AJAX 进行图像预览