【问题标题】:JQuery .load() function doesn’t work because file loaded contains small JSJQuery .load() 函数不起作用,因为加载的文件包含小 JS
【发布时间】:2019-08-24 18:10:50
【问题描述】:

两个 html 文件被包含到另一个 html 文件中,遵循这篇文章的建议:(Include another HTML file in a HTML file)。正在使用 JavaScript 来实现这一点,但是其中一个文件可以完美加载,而另一个则不能,因为它包含一个小的 JavaScript。我想知道是否有一种方法可以解决这个问题,而不必使用与 JavaScript 不同的方法来包含。请帮帮我。

我已经用其他包含测试了 JS,它就像一个魅力。当我从包含中删除小 JS 时,它可以工作,但 JS 需要在包含中。 Google 和 StackOverflow 没有解决这个问题的方法。

这是通过 JS 加载的包含 (footer.html),它不会加载:

                    <p>
                        Copyright &copy;
                        <script>
                            document.write(new Date().getFullYear());
                        </script> All rights reserved | This template is made with <i class="fa fa-heart-o" aria-hidden="true"></i> by <a href="https://colorlib.com" target="_blank">Colorlib</a>
                    </p>

如您所见,有一个小 JS 会阻止文件加载。

这是通过 JS 加载 footer.html 的 html 文件:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>This is a Webpage</title>
    <SCRIPT src="js/jquery-3.2.1.min.js"></SCRIPT>
<script>
  $(function(){
    var includes = $('[data-include]');
    jQuery.each(includes, function(){
      var file = '/en/inc/' + $(this).data('include') + '.html';
      $(this).load(file);
    });
  });
</script>
</head>
<body>
<div data-include="menu"></div>
<BR><BR><BR>
Content goes here
<BR><BR><BR>
<div data-include="footer"></div>
</body>
</html>

整个网页被阻止。这意味着您只会看到数字“2019”而不是网页。

【问题讨论】:

  • 加载后从不 document.write
  • 这个问题是由无法再复制的问题或简单的印刷错误引起的。虽然类似的问题可能是这里的主题,但这个问题的解决方式不太可能帮助未来的读者。
  • 在包含 jquery 之后在$(document).load(function(){ }) 中添加您的 javascript 代码,另一个建议不要在头部添加脚本标签,而是在正文的末尾添加
  • "在包含 jquery 之后在 $(document).load(function(){ }) 中添加您的 javascript 代码" 以前的建议我不明白 @mplungjan
  • 我在正文末尾有脚本标签,但脚本不起作用;然后我把它放在head 中,它确实做到了@mplungjan

标签: javascript include


【解决方案1】:

脚本完成并加载文档后将插入另一个页面,因此document.write将替换当前页面。

不要使用document.write - 使用 DOM 方法来选择和插入文本,例如:

<p id="rights"></p>
<script>
  document.querySelector('#rights').innerHTML = `Copyright &copy; ${new Date().getFullYear()}
  All rights reserved | This template is made with <i class="fa fa-heart-o" aria-hidden="true"></i> by <a href="https://colorlib.com" target="_blank">Colorlib</a>`;
</script>

(如果包含该子页面的所有页面也使用jQuery,您可以使用它来代替document.querySelector

【讨论】:

  • 问题解决了。十分感谢大家。然而,通过使用这个脚本,我试图解决我在这篇文章 (stackoverflow.com/questions/57595521/…) 中解释的问题。我的问题没有得到解决。请问有谁可以帮帮我吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-13
相关资源
最近更新 更多