javascript - jQuery加载函数页面加载问题

标签 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 中,但没有任何变化。 知道这里可能出了什么问题吗?

最佳答案

使用回调...

这是一个来自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...这里有更多详细信息...也不要直接从文件系统加载文件

$(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/

相关文章:

javascript - jQuery 适用于 Heroku,但不适用于 Rails localhost

javascript - 隐藏/显示 "back"上的元素(移动设备)

局部 View 中的 Javascript 如果局部 View 在页面上多次出现,如何让它只出现一次

javascript - 触发选择框的 onChange 事件(Jquery Chosen)

javascript - 获取文本小于 1024 个字符的 reddit 帖子

javascript - 在 ant Design Form 中使用 setFieldsValue 时无法限制或更改用户输入

javascript - 如何在调整大小函数中只调用一次函数?

javascript - 动态渲染 .mht 文件,无需加载/iframe/嵌入

javascript - 如何比较元素的 margin-left 与负值

javascript - 如何识别webp图片是静态图片还是动画图片?