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

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

问题描述

昨天我有一个问题,一个 .on('click')事件处理程序我正在分配不正确。原来是因为在DOM中存在该元素之前,我正在尝试应用 .on('click'),因为它是通过AJAX加载的,因此没有当 document.ready()已经到了这个时候,不存在。



我用尴尬的方法解决了解决方法,但我的问题是,如果我要在ajax加载的内容和另一个 document.ready()<< script> / code>在那个,那个第二个 document.ready()只有在ajax内容被加载完成时才被解析?换句话说,它是否认为单独加载的ajax内容是另一个文档,如果是,还有另一个 document.ready()

另外,什么是更好的办法处理这种情况? (需要在 document.ready())上添加一个事件监听器到一个不存在的DOM元素

解决方案

回答您的问题:否,一旦ajax请求完成,document.ready将不会再次启动。 (ajax中的内容被加载到你的文档中,所以没有第二个文档的ajax内容)。



为了解决你的问题,只需添加事件监听器到您将ajax内容加载到的元素。
例如:

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

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



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


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.

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?

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())

解决方案

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).

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 ));
});

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.

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天全站免登陆