【问题标题】:Can't make <header> and <footer> shared across pages无法使 <header> 和 <footer> 跨页面共享
【发布时间】:2021-11-09 18:29:57
【问题描述】:

我试图将

放在外部文件中。在控制台中,代码输出正常,但随后代码返回 undefined。

页脚 HTML:

<footer id="footer" class="footer mt-auto py-3 bg-light">
<div class="container">
    <div class="col-12 text-center">
        <a style="text-anchor: middle">© 2021 AlexInCube</a>
    </div>
</div>

main.html

<script>document.write(importHTMLdata("content/basement.html"))</script>

scripts.js

function importHTMLdata(path){
    $.get(path, function(html_string)
    {
        console.log(html_string)
        return html_string;
    });

【问题讨论】:

  • document.write 覆盖现有文本,所以不好用
  • stackoverflow.com/q/54924823/16846346 尝试从中获取参考
  • @Rana 如果像这里这样内联使用它是“好的”,它不会覆盖任何东西。 “好的”,我的意思是它按预期工作,当然不推荐。但是$.get 是异步的,这是 OP 的问题,所以它尝试的时候没有任何写入。

标签: javascript html jquery css bootstrap-4


【解决方案1】:

不建议使用 document.write - 如果在页面加载后执行它会擦除页面。

在你的 js 文件中加入这个

$(function() { // on page load
  const importHTMLdata = path => { // define a function taking a path
    $.get(path, function(html_string) { // get the path
      $("body")[path.indexOf("footer") != -1 ? "append" : "prepend"](html_string); // if footer call $("body").append, if not call $("body").prepend
    });
  }
  importHTMLdata("content/header.html"); // load header
  importHTMLdata("content/footer.html")  // load  footer
});
<script src="scripts.js"></script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-04
    相关资源
    最近更新 更多