【问题标题】:Why does jQuery's load() require extra code? What should this extra code be?为什么 jQuery 的 load() 需要额外的代码?这个额外的代码应该是什么?
【发布时间】:2015-04-14 13:39:55
【问题描述】:

在我的 index.html 中,我有一堆空的部分标签。每个部分标签从单独的文件中接收其各自的 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>

section-loader.js

$('#section1').load('section1.html');
$('#section2').load('section2.html');
$('#section3').load('section3.html');

当我第一次加载所有内容时,它会将每个部分的 HTML 加载到 index.html 中各自的部分标签中。这正是我想要发生的事情。

但是,当我刷新页面或打开它的新实例时,这些加载调用都不会发生。

我向 section-loader.js 添加了一个警报,以查看该页面是否被第二次调用,但我收到了意外的结果。该警报导致一切都按照我想要的方式第二次运行(除了不需要的警报)。

我希望我已经解释得足够好。这对我来说是很奇怪的行为。

我有两个问题:

  • 为什么会这样?
  • 修复它的最佳方法是什么?

【问题讨论】:

  • 重新加载(开发工具)后“网络”选项卡会发生什么?
  • 尝试在section-loader.js里面运行$(document).ready()中的代码。
  • @OddDev 只有 200 秒
  • @SalmanA 这就是我的想法,但似乎发生了一些奇怪的时间安排。由于它只发生第二次,我怀疑它也涉及缓存。
  • @Evorlor 能否请您禁用 devtools 中的缓存(F12 -> cog -> 为 Chrome 勾选“禁用缓存(在 DevTools 打开时)”)并再次重新加载 while DevTools 仍然打开?

标签: javascript jquery html modularity


【解决方案1】:

你必须等待 onload 事件,对于 jQuery 这个:

$(function() {
    $('#section1').load('section1.html');
    $('#section2').load('section2.html');
    $('#section3').load('section3.html');
});

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-09
  • 1970-01-01
  • 2020-10-08
  • 1970-01-01
  • 1970-01-01
  • 2019-12-14
  • 2018-07-20
相关资源
最近更新 更多