JQuery加载函数页面加载问题

时间:2016-03-11 10:20:50

标签: javascript jquery html css

我有一个main.html,我正在尝试加载另一个HTML。 main.html中的代码是这样的:

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

在sample.html中,我有另一个JavaScript无法按预期工作。

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

我甚至没有正确获得元素的宽度。令人惊讶的是,如果我在JavaScript中设置断点或发出警报,那么一切似乎都运行良好。这让我觉得脚本运行时可能没有加载页面,通过设置警报或断点会给它多一点时间?我在网上进行了一些搜索并认为加载不同步,这意味着在页面加载之前,sample.html页面内的脚本正在执行。这只是我的猜测。 我已经尝试过添加JQuery函数并在sample.html中加载,但没有任何变化。 知道这里有什么不对吗?

1 个答案:

答案 0 :(得分:0)

使用回调...

这是doku的一个例子

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

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

并且还使用jQuery&#39;

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

当dom准备就绪时,Document ready会触发回调。加载文件时,load会触发回调。

<强> //修改 请使用文档准备...这里有更多详细信息...并且不直接从文件系统加载文件

$(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) 
   });


}