jQuery事件等待数据加载到页面中

jQuery event wait until the data gets loaded in page

本文关键字:加载 事件 等待 数据 jQuery      更新时间:2023-09-26

我正在使用$("div").load(url)事件在页面中加载我的部分视图。以便该页面呈现得更快。但是有了这个$(document).ready甚至在加载内容之前就被触发了。我也尝试过$(window).load,但这甚至在内容加载之前就被触发了。

您能否建议一种方法等到数据加载,然后只执行我的javascript函数。

当您使用 $("div").load(url) 时,您将异步加载 url 内容。这意味着首先初始化 document.load,然后对 load(url) 进行异步调用。

将所有初始化的Javascript放在一个函数中(假设myinit()),并在成功调用加载方法时触发它例如

// this line keeps all your function in one global name space and you can extend it multiple times in same document or js files
var myapp = myapp||{}; 
$(function(){
    // Here you are extending your myapp object with custom init function
    myapp.init = function(){
        //your init code here
    }
    //your ajax content load here
    $('div').load(url,function(){
        //Here you call it
        myapp.init();
    })
})

附言:您始终可以在控制台中使用 myapp.init() 在 jQuery exec 块中的任何位置测试您的自定义方法