我有一个 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 中,但没有任何变化。 知道这里可能出了什么问题吗?
最佳答案
使用回调...
这是一个来自doku的例子
$( "#result" ).load( "ajax/test.html", function() {
alert( "Load was performed." );
});
也可以使用 jQuery 的
$( document ).ready(function() {
console.log( "ready!" );
});
当 dom 准备就绪时,文档就绪会触发回调。加载文件时会触发回调。
//编辑 请使用 document ready...这里有更多详细信息...也不要直接从文件系统加载文件
$(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 - jQuery加载函数页面加载问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35937593/