Javascript JQuery加载函数页面加载问题
我有一个main.html,试图在其中加载另一个html。 main.html中的代码如下所示:Javascript JQuery加载函数页面加载问题,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我有一个main.html,试图在其中加载另一个html。 main.html中的代码如下所示: <script type="text/javascript"> $(window).load(function(){ $("#divid").load("sample.html"); }); </script> $(窗口)。加载(函数(){ $(“#divid”).load(“sample.html”); }); 在sample.html中,我有另一个JavaS
<script type="text/javascript">
$(window).load(function(){
$("#divid").load("sample.html");
});
</script>
$(窗口)。加载(函数(){
$(“#divid”).load(“sample.html”);
});
在sample.html中,我有另一个JavaScript,它不能按预期工作
<!-- inside sample.html -->
<script type="text/javascript">
... Some JavaScript here ...
</script>
... 这里有一些JavaScript。。。
我甚至无法正确获取元素的宽度。令人惊讶的是,如果我在JavaScript中设置了一个断点或设置了一个警报,所有这些似乎都可以正常工作。这让我猜测,当脚本运行时,页面可能不会被加载,而通过放置警报或断点,会给它更多的时间吗?我在web上进行了一些搜索,认为加载不同步,这意味着sample.html页面中的脚本在页面加载之前执行。这只是我的猜测。
我也尝试过在sample.html中添加JQuery函数,但没有任何变化。
知道这里有什么问题吗?使用回调
这是一个来自doku的例子
$( "#result" ).load( "ajax/test.html", function() {
alert( "Load was performed." );
});
并使用jQuery的
$( document ).ready(function() {
console.log( "ready!" );
});
documentready在dom就绪时触发回调。和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)
});
}
我不是JavaScript方面的专家,你能再解释一下吗?你是说当我的sample.html准备好时加载回调会触发吗?我应该在回调中做什么?在仔细考虑了您的意思之后,我做了以下操作:
$(window.load(function(){$(“#divid”).load(“sampleHtml/sample.html”,function(){sampleHtmlFn(););})
并在函数sampleHtmlFn()内编写sample.html内的JavaScript。但结果是一样的。用更多的细节来扩展答案。您还应该查看jQuery文档。