简体   繁体   English

JQuery: append 元素出现后和AJAX 元素如何出现?

[英]JQuery: How to append element after and element appears with AJAX?

I have a modal that is loaded via AJAX (I have no access to the JS files that trigger this).我有一个通过 AJAX 加载的模式(我无权访问触发它的 JS 文件)。

I want to use JQuery to append some HTML to the body of the modal.我想使用 JQuery 到 append 一些 HTML 到模态的主体。

If course I can't simply do that within a document.ready function.如果我当然不能在文档中简单地做到这一点。就绪 function。

Is there a way to append the HTML when another element appears in the DOM?当另一个元素出现在 DOM 中时,有没有办法将 append 变为 HTML?

I've tried我试过了

    $('.npopup .description').load(function(){
        $(this).append(message);
    });

and

    $('.npopup .description').ready(function(){
        $(this).append(message);
    });

with no results.没有结果。

You may use the ajaxComplete() like that:您可以像这样使用ajaxComplete()

$( document ).ajaxComplete(function( event, xhr, settings ) {
  if ( settings.url === "ajax/test.html" ) {
    $(this).append(message);
  }
});

Make sure you give a look at the event , xhr and settings to let you find what request you are interested in. Otherwise, if you don't use the if statement in the body of the callback, you will append the message in every ajax call.请务必查看eventxhrsettings ,以便找到您感兴趣的请求。否则,如果您不在回调正文中使用if语句,您将在每个 ajax 中收到 append 消息称呼。

Another possible solution is to listen for changes in the DOM using the MutationObserver.另一种可能的解决方案是使用 MutationObserver 监听 DOM 中的变化。 See for example here: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver .请参阅此处的示例: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

The MutationObserver is a better solution though, but I don't remember what is the compatibility with the browsers. MutationObserver 虽然是一个更好的解决方案,但我不记得与浏览器的兼容性如何。 Generally speaking, the compatibility is quite good.总的来说,兼容性还是不错的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM