Live()关键字在动态加载HTML图像时无效

4

我正在动态地向页面添加图片,但是我似乎无法使用live()动态地使“load”事件起作用。

这是我目前的代码:

$('#largeImg' + nextUniqueItemID).hide();
$('#largeImg' + nextUniqueItemID).live('load' , function() {
    $('#loader' + nextUniqueItemID).hide();
    $('#largeImg' + nextUniqueItemID).show();
});

'#largeImg' + nextUniqueItemID 是在此函数前添加到页面中的图像,'#largeImg' + nextUniqueItemID 是一个加载图像。

我感觉使用 "live" 可能有误,因为它不需要监听器而是立即触发事件。

感谢您提供的所有帮助。我尝试了 "bind" 但从未触发。我还尝试去除加载,但那没用。是否有一种方法可以附加事件侦听器来指示图像何时加载完成?

5个回答

6
我认为jQuery文档在这方面可能有些误导,除非它采用了一些特殊方法来解决这个问题。
像图片这样的元素上的加载事件不会冒泡。1, 2 由于它们不会冒泡,所以document不知道是否已经触发了加载事件。
因为document不知道加载事件,所以live将变得无用。因为live依赖于事件冒泡到document,一旦这样做,它就会将事件目标与其已有的选择器进行匹配,如果有任何匹配,就会为该元素触发事件处理程序。
例如,假设您要注册以下live事件:
$("#container > input").live("change", function() {
    alert("changed");
});

如果尚不存在,则jQuery将在文档对象上添加更改事件侦听器(类似于):
$(document).bind("change", function() {
    ..
});

任何变更事件冒泡到文档时,它会遍历每个已注册的选择器,并检查给定选择器的所有结果节点中是否包括事件目标(事件起源元素)。如果存在,则相应的“实时”事件处理程序将为该事件目标触发。

如果文档一开始就不知道事件,那么这一切都是不可能的。

除非我弄错了,jQuery没有什么秘密酱来做到这一点,你应该直接绑定加载事件,而不是通过live进行。

$("selector").bind("load", function() { .. });

1

这段代码在哪里??

$('#largeImg' + nextUniqueItemID).hide();
$('#largeImg' + nextUniqueItemID).live('load' , function() {
$('#loader' + nextUniqueItemID).hide();
$('#largeImg' + nextUniqueItemID).show();
});

如果这是在jQuery ajax的回调函数中,你不必使用.live(),可以使用.bind()


0
我会查看文档: http://api.jquery.com/live/
* In jQuery 1.3.x only the following JavaScript events (in addition to custom events) could be bound with .live(): click, dblclick, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, and mouseup.

    * As of jQuery 1.4 the .live() method supports custom events as well as all JavaScript events. As of jQuery 1.4.1 even focus and blur work with live (mapping to the more appropriate, bubbling, events focusin and focusout).
    * As of jQuery 1.4.1 the hover event can be specified (mapping to "mouseenter mouseleave").

无论是什么触发了创建,都应该触发与load事件一起使用的项目的隐藏和显示。

0
你尝试过使用属性选择器而不是直接使用ID吗?
$('#largeImg' + nextUniqueItemID).hide();
$('[id=largeImg' + nextUniqueItemID + ']').live('load', function() {
    $('#loader' + nextUniqueItemID).hide();
    $('[id=largeImg' + nextUniqueItemID + ']').show();
});

-1
我最终做的是直接将加载事件放在我的图像的 onLoad="" 事件中。这样就可以了。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接