【问题标题】:How do I import html into another html document?如何将 html 导入另一个 html 文档?
【发布时间】:2017-06-12 16:23:36
【问题描述】:

我试图将导航保存在一个 html 文件中,而不是将其复制并粘贴到每个文件中,因此如果我想更改某些内容,我不必编辑每个文件。我想将导航代码包含到我的文件中,但到目前为止我尝试过的任何事情都没有按照我想要的方式工作。我想只使用 html/css/js 来做到这一点,这似乎是一种简单的方法,因为它在很多项目中都很实用。

到目前为止我已经尝试过

object/iframe - 将代码嵌入到它的迷你窗口中,而不是想要的结果。

javascript object.write - 正在导入的文件中已删除的代码。

w3.includehtml - 可以在 Firefox 中使用,但不能在 chrome 中使用,我不知道为什么。我们将不胜感激,因为这似乎是最好的方法。

php include-没用,可能是因为我不了解php并且很可能做错了什么,如果有人可以告诉我如何或链接教程,我愿意接受。

【问题讨论】:

  • jquery 在 $.load() 上做得很好
  • 或者您可以通过 stackoverflow.com/questions/38132510/… 使用 vanilla JS 来完成此操作
  • @Jonasw 你读过这个问题吗......
  • @epascarello 我认为他并没有真正尝试过......基本上是css样式的问题

标签: javascript html css


【解决方案1】:

将组件创建为模板,例如:

nav.template.html

<template>
  <nav><!-- nav stuff here ... there has to be only one childNode of template because of how we will mount it, but you could change that -->
  <style scoped>/* you can style only nav content directly here if you like */</style>
  </nav>
</template>

然后,在 domready 上使用 javascript 加载它,例如:

site.js

document.addEventListener('DOMContentLoaded', function() { // there are more thorough, extensible ways of attaching to this event ..
    let el = document.querySelector('.nav-mount-point')
    // I'm doing to use axois, assuming you load it from a CDN or directly. You could also do this with plain AJAX, etc
    axios.get('path/to/nav.template.html')
      .then(res => {
        let dt = document.createElement('div')
        dt.innerHTML = res.data
        el.appendChild(dt.children[0].content.cloneNode(true))
      })
      .catch(e => console.error(e))
}, false);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-08
    • 1970-01-01
    • 2010-10-19
    • 2017-10-11
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2014-01-19
    相关资源
    最近更新 更多