你能链接到HTML文件吗?

Emm*_*ies 4 html html5

我的网站始终使用相同的导航菜单,而不是为每个页面重写HTML代码,我可以像使用CSS一样链接到第二个HTML文件(包含导航HTML代码)吗?或者这会产生问题吗?

pri*_*esh 9

简单的方法是将标题部分放在一个单独的html文件中.

现在使用jQuery load函数在html代码中加载此文件

$("#headerDiv").load("header.html")
Run Code Online (Sandbox Code Playgroud)

要知道,这将需要Web服务器,因为加载功能向服务器发送请求.

查看代码示例:

demo.html

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script> 
   $(function(){
    $("#headerDiv").load("header.html");
   });  
</script>
</head>
<body>
<div id="headerDiv"></div>
<!-- Rest of the code -->
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

了header.html

<div >
    <a>something</a>
    <a>something</a>        
</div>
Run Code Online (Sandbox Code Playgroud)

  • 这个方法与这个方法有什么对比,`<div w3-include-html ="content.html"> </ div>`?哪个更好? (2认同)

Mi-*_*ity 5

对于HTML解决方案 - 因为您的问题中没有其他标记 - 有HTML导入:

<link rel="import" href="nav.html">
Run Code Online (Sandbox Code Playgroud)

但是这个新的工作草案 - 并没有很好的浏览器支持.


资源:


Pmp*_*mpr 5

这就是所谓的HTML include和YES,这是可能的

<div w3-include-HTML="content.html">My HTML include will go here.</div>
<script>
(function () {
  myHTMLInclude();
  function myHTMLInclude() {
    var z, i, a, file, xhttp;
    z = document.getElementsByTagName("*");
    for (i = 0; i < z.length; i++) {
      if (z[i].getAttribute("w3-include-html")) {
        a = z[i].cloneNode(false);
        file = z[i].getAttribute("w3-include-html");
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
          if (xhttp.readyState == 4 && xhttp.status == 200) {
            a.removeAttribute("w3-include-html");
            a.innerHTML = xhttp.responseText;
            z[i].parentNode.replaceChild(a, z[i]);
            myHTMLInclude();
          }
        }      
        xhttp.open("GET", file, true);
        xhttp.send();
        return;
      }
    }
  }
})();
</script>
Run Code Online (Sandbox Code Playgroud)

笔记

HTML没有简单的包含机制(iframe之类的框架除外,它具有副作用)。

更好的解决方案是使用Server-Side includes,当然,这是在服务器上向文档添加通用部分的首选方式。