在我的index.html中,我有一堆空的section标记。每个section标记从一个单独的文件中接收其各自的HTML代码。我的设置如下:
index.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Using jQuery's load()</title>
</head>
<body>
<section id="section1"></section>
<section id="section2"></section>
<section id="section3"></section>
<script src="//code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="assets/js/section-loader.js"></script>
</body>
</html>
section1.html
<h1>Section 1</h1>
section2.html
<h2>Section 2</h2>
section3.html
<h3>Section 3</h3>
区段加载器.js
$('#section1').load('section1.html');
$('#section2').load('section2.html');
$('#section3').load('section3.html');
当我第一次加载所有内容时,它会将每个部分的HTML加载到index.HTML中各自的部分标记中。这正是我想要的。
但是,当我刷新页面或打开它的新实例时,这些加载调用都不会发生。
我在section-loader.js中添加了一个警报,以查看第二次是否调用了该页面,但我收到了意外的结果。警报导致一切都按照我想要的方式第二次运行(除了不需要的警报)。
我希望我已经解释得足够好了。这对我来说是非常奇怪的行为
我有两个问题:
- 为什么会发生这种情况
- 修复它的最佳方法是什么
您必须等待onload事件,对于jQuery this:
$(function() {
$('#section1').load('section1.html');
$('#section2').load('section2.html');
$('#section3').load('section3.html');
});