当内容是动态的 ajax (Lightbox) 时如何触发不显眼的 javascript
我有一些来自 ajax 的链接需要灯箱功能:
<a href="..." class="lightbox"><img src='...'></a>
通常这是通过页面加载处理程序给出的行为,但由于内容来自 ajax,因此 UJS 不会被触发。
有办法做到这一点吗?
I've got some links coming in from ajax that need lightbox functionality:
<a href="..." class="lightbox"><img src='...'></a>
Normally this is given behavior via an on page load handler, but since the content is coming from ajax, the UJS isn't getting triggered.
Any way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果内容来自 AJAX,则不要在页面加载期间设置事件处理。相反,让事件冒泡到未被 AJAX 更改或替换的最顶层容器。最坏的情况,使用
document
作为最顶层的节点。If the content is coming from AJAX, then din't setup the event handling during page load. Instead, let the event bubble to the topmost container that is not being changed or replaced by AJAX. Worst case, use
document
as the topmost node.我不确定你是如何触发 ajax 请求的,但如果使用 jQuery(这似乎是可能的),你可以在成功回调中绑定灯箱:
你可以将上下文传递给 jQuery 选择器,这样你就不会重新 -将灯箱附加到页面中已有的链接,例如,如果您的 ajax 调用将链接添加到 id 为“lightbox_links”的 div,请改用此选择器:
I'm not sure how you're triggering the ajax requests, but if it's with jQuery which seems likely, you can bind the lightbox in the success callback:
You can pass in a context to the jQuery selector so you don't re-attached the lightbox to links that are already in the page, for example if your ajax call is adding the links to a div with id 'lightbox_links', use this selector instead: