AJAX 加载的内容是否获得“document.ready"? [英] Does AJAX loaded content get a "document.ready"?

查看:21
本文介绍了AJAX 加载的内容是否获得“document.ready"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

昨天我遇到了一个问题,我分配的 .on('click') 事件处理程序无法正常工作.原来这是因为我试图在该元素存在于 DOM 之前应用该 .on('click') ,因为它是通过 AJAX 加载的,因此当document.ready() 到此为止.

Yesterday I had an issue where a .on('click') event handler I was assigning wasn't working right. Turns out it's because I was was trying to apply that .on('click') before that element existed in the DOM, because it was being loaded via AJAX, and therefore didn't exist yet when the document.ready() got to that point.

我用一个尴尬的解决方法解决了它,但我的问题是,如果我要在 ajax 加载的内容和另一个 document.ready() 在其中,第二个 document.ready() 是否仅在加载完 ajax 内容后才被解析?换句话说,它是否认为单独加载的 ajax 内容是另一个 document,如果是,那么在该 ajax 加载的 HTML 中是否有另一个 document.ready()我认为它的方式是什么?

I solved it with an awkward workaround, but my question is, if I were to put a <script> tag IN the ajax loaded content and another document.ready() within that, would that second document.ready() be parsed ONLY once that ajax content is done being loaded? In other words, does it consider that separately loaded ajax content to be another document, and if so, does having another document.ready() within that ajax-loaded HTML work the way I think it does?

或者;处理这种情况的更好方法是什么?(需要将事件监听器附加到 document.ready() 上尚不存在的 DOM 元素)

Alternatively; what would be a better way to handle this situation? (needing to attach an event listener to a DOM element that doesn't yet exist on document.ready())

推荐答案

回答您的问题:不,一旦 ajax 请求完成,document.ready 将不会再次触发.(ajax 中的内容已加载到您的文档中,因此 ajax 内容没有第二个文档).

To answer your question: No, document.ready will not fire again once a ajax request is completed. (The content in the ajax is loaded into your document, so there isn't a second document for the ajax content).

要解决您的问题,只需将事件侦听器添加到您将 ajax 内容加载到其中的元素中.例如:

To solve your problem just add the event listener to the Element where you load the ajax content into it. For example:

$( "div.ajaxcontent-container" ).on( "click", "#id-of-the-element-in-the-ajax-content", function() {
  console.log($( this ));
});

对于 #id-of-the-element-in-the-ajax-content,您可以使用在 $("selector") 中使用的任何选择器.唯一不同的是,只有 div.ajaxcontent-container 下的元素会被选中.

For #id-of-the-element-in-the-ajax-content you can use any selector you would use in $("selector"). The only difference is, only elements under div.ajaxcontent-container will be selected.

工作原理:只要 div.ajaxcontent-container 存在与选择器 #id-of-the-element-in-the-ajax 匹配的所有元素(如果它们现在存在或仅在将来存在)-content 将触发此点击事件.

How it works: As long as div.ajaxcontent-container exists all elements (if they exist now or only in the future) that match the selector #id-of-the-element-in-the-ajax-content will trigger this click-event.

这篇关于AJAX 加载的内容是否获得“document.ready"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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