jQuery加载函数页面加载问题 [英] JQuery load function page loading issue

查看:179
本文介绍了jQuery加载函数页面加载问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个main.html,其中我试图加载另一个HTML。
main.html中的代码如下:

I have a main.html in which I am trying to load another HTML. The code in main.html is like this:

<script type="text/javascript">
$(window).load(function(){
    $("#divid").load("sample.html");
});
</script>

在sample.html中,我有另一个JavaScript不能正常工作。

Inside the sample.html, I have another JavaScript which doesn't work as expected.

<!-- inside sample.html -->
<script type="text/javascript">
... Some JavaScript here ...
</script>

我甚至不能正确获取元素的宽度。令人惊讶的是,如果我在JavaScript中放置一个断点或者提醒,似乎都很好。这让我猜测,页面可能不会加载脚本运行时,通过提醒或断点给它一点时间?我在网上进行了一些搜索,认为加载不同步,这意味着在sample.html页面内的脚本在页面加载之前正在执行。这只是我的猜测。
我已经尝试添加JQuery函数ready和加载在sample.html中,但没有任何变化。
任何想法在这里可能出错了什么?

I do not even get the width of an element correctly. Surprisingly, if I put a breakpoint in the JavaScript or put an alert, all seem to work well. This made me guess that page might not be loaded when script runs and by putting alert or breakpoint gives it a bit more time ? I did some searching on web and think that the loading is not in sync which means that the script inside the sample.html page is executing before the page could load. This is just my guess. I have tried adding JQuery functions ready and load inside the sample.html as well but nothing changes. Any idea what could be wrong here ?

推荐答案

使用回调...

这是doku的示例

    $( "#result" ).load( "ajax/test.html", function() {
  alert( "Load was performed." );
});

http://api.jquery.com/load/

并使用jQuery的

$( document ).ready(function() {
    console.log( "ready!" );
});

当dom准备就绪时,文档准备就绪触发回调。

Document ready fires the callback, when the dom is ready. And load fires the callback when the file is loaded.

// EDIT
请使用文件准备...这里有更多详细信息...并且不能直接从文件系统加载文件

//EDIT Please use document ready... here are more details... and also do not load files directly from the file system

$(document).ready(function(){
  // You will enter here, wenn the DOM is loaded and ready to use

  //When everything is ready to roll you want to  load your html file
   $("#divid").load("sample.html",function(){
     // You will enter this method when sample.html is loaded

     // Make sure there is also a div with the id=divid 
     // to get details on why this is not loading you can also use the
     // function signature  
     // $("#divid").load("sample.html",function(responseText, textStatus, jqXHR){});
     // You should also be aware of loading a file from file system can cause to ajax 
     // errors if it is not served by an http server. Because you can't access local
     // files from within JavaScript (security thing) 
   });


}

这篇关于jQuery加载函数页面加载问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆