jQuery的事件不会为附加元素工作 [英] jquery events doesn't work for appended elements

查看:110
本文介绍了jQuery的事件不会为附加元素工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个网站这里

正如你可以看到有一个很小的图像滑块图像和网页模板选项卡,其中的图像由右至左滑动,然后消失,然后出现在父元素的最后(一个< TR方式> 在我的情况)

As you can see there is a tiny image slider for "Images" and "Web Templates" tabs where the images are sliding from right to left, then disappears and then it appears at the very end of the parent element (an <tr> in my case).

如果你将鼠标悬停在小图像,你可以看到它的左侧preVIEW。

If you hover over the small images you can see it's preview on the left.

到目前为止好。

但如果你等到的第一印象再来时,悬停事件不工作了。

But if you wait until the first images comes again, the hover event doesn't work anymore.

这可能是jQuery的看不到新的附加元素在&LT的结束; TR&GT; 标记?

It is possible that jquery can't see that new appended elements at the end of the <tr> tag?

推荐答案

要绑定你的事件将不会对动态地添加元素的工作方式。在preview_script.js您有:

The way you are binding your events will not work for dynamically added elements. In preview_script.js you have:

$(".box_body img").hover(function(){

这将添加事件处理器到所有的img标签带班box_body,而那些在后面追加不会得到该事件。

This will add eventhandlers to all img tags with class "box_body", but ones that are appended later will NOT get the event.

试试这个:

$(document).on("hover", ".box_body img", function() {..});

这将增加记录的情况下,只有火,如果该事件目标是IMG与类=box_body。由于事件传播了这个应该达到的文件之前,工作,只要没有在站之间(通过调用event.stopPropagation())

This will add the event to document, and only fire it if the eventtarget is img with class = "box_body". Since events propagate up this should work as long as nothing in between stops it before it reaches document (by calling "event.stopPropagation()")

如果您知道.box_body IMG家长可以替换该文件,这将工作更好一点,你不必等待事件传播到文件。

If you know the PARENT of ".box_body img" you can replace document with that, this will work a little better as you don't have to wait for the event to propagate up to document.

请注意,您可以通过完成委托同样的事情(如果不可用):

Note that you can accomplish the same thing using delegate (if on is not available):

$(document).delegate(".box_body img", "hover", function() {..});

这篇关于jQuery的事件不会为附加元素工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆