Live()关键字无法使用动态html图像加载

我将图像动态添加到页面中,我似乎无法使用live()动态地使用’load’事件。

这是我目前的代码:

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

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

我觉得好像我可能会滥用“直播”,因为它不需要听众,而是立即触发事件。

感谢你的帮助。 我试过“绑定”而且从未触发过。 我也尝试消除负载,但这不起作用。 有没有办法将一个监听器附加到一个事件,该事件将指示图像何时加载?

我认为jQuery文档在这个问题上可能会有点误导,除非它正在做一些非常特殊的事情来解决这个问题。

在诸如图像之类的元素上加载事件不会冒泡。 1,2

由于它们没有冒泡,因此document不知道是否已触发加载事件。

因为document不知道加载事件,所以live会渲染无用,因为live依赖于冒泡到文档的事件,一旦它们这样做,它就会将事件目标与它已存在的选择器匹配,如果匹配的话,为该元素触发事件处理程序。

例如,假设您要注册以下直播活动:

 $("#container > input").live("change", function() { alert("changed"); }); 

那么jQuery将在文档对象上添加一个更改事件监听器(如果它尚不存在)(类似于):

 $(document).bind("change", function() { .. }); 

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

如果文件首先不知道该事件,那么这一切都不可能。

除非我弄错了并且jQuery有一些秘密的做法,你应该直接绑定load事件而不是通过live来实现。

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

这段代码在哪里?

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

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

我会查看文档: 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事件的项目。

您是否尝试使用属性选择器而不是直接ID?

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

我最终做的是将load事件直接放在我的图像的onLoad =“”事件中。 结果很好。