简体   繁体   English

运行 jquery 一旦 div 的内容已完全加载

[英]Run jquery Once content of a div has fully loaded

I have a div am-events-booking that is dynamically loaded using Javascript and this div normally takes a second or so to load after the page has loaded.我有一个使用 Javascript 动态加载的 div am-events-booking ,并且该 div 通常在页面加载后需要一秒钟左右的时间才能加载。 I would like to run a jQuery code once the contents of this div has fully loaded.一旦这个 div 的内容完全加载,我想运行 jQuery 代码。

Below is the workaround i have used to delay the running of the script by 5000ms however this doesn't seem to be correct as if the page load takes more than 5000ms then the script would not run.下面是我用来将脚本运行延迟 5000 毫秒的解决方法,但这似乎不正确,因为如果页面加载时间超过 5000 毫秒,那么脚本就不会运行。 Is there are better way to do this?有没有更好的方法来做到这一点? May be use mutations and if so, how do I go about it?可能是使用突变,如果是这样,我该怎么做 go 呢?

 jQuery(document).ready(function($) { $(document).ready(function() { var i = setInterval(function() { if ($("#am-events-booking").text().length > 0) { clearInterval(i); $(".am-event-data").addClass('bg'); } else { console.log("Waiting..."); } }, 5000); console.log("Page is loaded"); }); });
 .am-event-data { border: 1px solid black; padding: 10px; width: 50%; }.bg { background: red; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="am-events-booking"> <div class="am-event-data"> <div class="am-event-date"> <div class="am-event-date-month" style="color: rgb(249, 169, 126);">Mar</div> <div class="am-event-date-day">24</div> </div> <div class="am-event-info"> <div class="am-event-title">Ballet <span class="am-event-booking-status open">Open</span></div> </div> </div> <div class="am-event-data"> <div class="am-event-date"> <div class="am-event-date-month" style="color: rgb(249, 169, 126);">April</div> <div class="am-event-date-day">25</div> </div> <div class="am-event-info"> <div class="am-event-title">Other <span class="am-event-booking-status open">Open</span></div> </div> </div> </div>

Have you taken a look at jQuery.on('load')?你看过 jQuery.on('load') 吗?

The following answer may help - https://stackoverflow.com/a/58871367/3907839以下答案可能会有所帮助 - https://stackoverflow.com/a/58871367/3907839

Alternatively, can you use something like this?或者,你可以使用这样的东西吗?

https://gist.github.com/chrisjhoughton/7890303#file-wait-el-js https://gist.github.com/chrisjhoughton/7890303#file-wait-el-js

So in your case, include the waitForEl function in your code and then use it.所以在你的情况下,在你的代码中包含 waitForEl function 然后使用它。 Take a read through the comments for relevant refactored code, I've just looked at the first bit.阅读相关重构代码的注释,我刚刚看了第一部分。

waitForEl($("#am-events-booking"), function() {
    $(".am-event-data").addClass('bg');
});

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

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