对 AJAX 添加的元素执行操作
我有一个带有灯箱的页面,使用灯箱插件。我想要变成灯箱的元素只需选择并更改如下:
$(".lightbox").find("a").live('click', function(e) { e.preventDefault(); $(".lightbox").find("a").fancybox({ 'transitionIn' : 'elastic', 'transitionOut' : 'elastic' }); });
我知道这不是最干净的方法,但它目前有效。我真正的问题是,如何在 AJAX 添加到页面的元素上运行 $(".lightbox").fancybox(...)
?我可以将 .fancybox()
内容放在 AJAX 调用的 success:
部分中,但我正在寻找一种更干净的“即发即忘”解决方案;我可以编写一段适用于所有未来元素的代码。 .live()
在这里非常完美,除了您必须将其绑定到事件之外。我猜这里的偶数是create
,它不存在。
那么,现在或将来如何对通过 AJAX 添加到页面的元素运行函数,而不必在各处放置大量代码呢?
谢谢,
詹姆斯
I have a page with a lightbox on it, using a lightbox plugin. The elements I want to turn into a lightbox are simply selected and altered like this:
$(".lightbox").find("a").live('click', function(e) { e.preventDefault(); $(".lightbox").find("a").fancybox({ 'transitionIn' : 'elastic', 'transitionOut' : 'elastic' }); });
I know it's not the cleanest way, but it works for now. My real question is, how can I run $(".lightbox").fancybox(...)
on elements added to the page by AJAX? I could put the .fancybox()
stuff inside the success:
part of the AJAX call, but I'm looking for a cleaner, "fire and forget" solution; one piece of code I can write that applies to all future elements. .live()
is perfect here, apart from the fact that you have to bind it to an event. I guess the even here is create
, which doesn't exist.
So, how can I run a function on elements added to the page by AJAX now, or in the future without having to put lots of bits of code all over the place?
Thanks,
James
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需在 jQuery ajax 调用之上添加另一层抽象即可。该层将为您进行 ajax 调用并扫描您的结果,并根据需要添加灯箱。这是我的想法:
1.
也许是这样的?但我不知道这在实践中效果如何。似乎您希望始终在将某些内容添加到 DOM 后触发某些功能。
或者
您还可以围绕
innerHTML
创建一个包装器来为您完成这项工作:2.
您可以调用
addHtmlToDomWithLightbox
在所有成功函数中(而不是通过 jQueryhtml
方法添加 html)。请注意,方法名称又长又冗长,您可以更改它并将方法放置在您想要的任何位置。我只是出于说明目的而将其变得冗长。Just add another layer of abstraction above your jQuery ajax call. This layer will make the ajax call for you and scan your result, adding the lightbox as necessary. Here is what I have in mind:
1.
Something like that maybe? I don't know how well that would work in practice though. It seems like you want to always trigger some function after something has been added to the DOM.
Alternatively
You could also create a wrapper around
innerHTML
to do the work for you:2.
You would call
addHtmlToDomWithLightbox
in all of your success functions (instead of adding the html via the jQueryhtml
method). Note that the method name is long and verbose, you could change it and place the method where ever you want. I just made it verbose for illustrative purposes.