在子页面中使用jQuery.load和$()。ready的时序问题

时间:2013-01-14 21:48:56

标签: jquery

我正在尝试在父页面上使用jQuery Load来动态插入URL中的某些子页面。在父页面中,我执行以下操作:

var html = gridDiv.load(self.options.url, function(html, status, xhr)
{
gridDiv.find("myObject:first").data("objectInstance");
    //do something....
});

数据对象实际上是在文档就绪运行的函数中添加到子页面中的。

$().ready(function()

我最初注意到的是,在本地运行时,一切都按预期工作。但是当部署在实际URL上时,load子事件会在子页面上的$()。ready之前触发。第一个问题是这是正确的,有没有任何解决办法,以便我可以在子页面上调用$()。ready之后运行我的代码?

我尝试了一种解决方法,在父页面中使用计时器来检查元素。在短暂的间隔之后,元素将出现在dom中,但数据在其上是空的。但是,如果我在一个按钮单击中运行调试器,我可以在那里看到它..

另一种解决方法是将脚本放在子页面的底部,然后删除文档。这也行不通。

有什么建议吗? (我无法修改子页面上的代码逻辑,它需要自包含)

2 个答案:

答案 0 :(得分:2)

当您在本地运行代码时,您实际上看不到加载时间延迟。您的代码存在问题

    $().ready(function(){})
    //executes when HTML-Document is loaded and DOM is ready

所以我建议你使用

    $(window).load(function(){});
    // executes when complete page is fully loaded, including all frames, objects, scripts and images

答案 1 :(得分:1)

您是否尝试将要执行的代码放入函数中,然后在子页面上调用该函数?

例如:

//main page
$.ajax({
    url: "child.html",
}).done(function(data, xhr, status){
    $('body').append(data);
});

function child_finished_loading(){
    alert('child is done!');
}

//returned through ajax (child)
<span>This is being appended to main page!</span>
<script type="text/javascript">
    $(function(){
        child_finished_loading();
    });
</script>
相关问题