繁体   English   中英

如何在另一个页面 html 中包含 html 和 javascript?

[英]How to include html and javascript in another page html?

我有一个文件,它有一个导航栏并与另一个文件交互,如 css 和 javascript 文件。 我需要做的是将此代码包含在另一个 html 页面中,我不知道该怎么做。 我使用 nodejs 作为服务器端,作为前端我使用 w3.css 和 w3.js。 你能帮我吗??

<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<script src="https://www.w3schools.com/lib/w3.js"></script>
<script src="https://kit.fontawesome.com/a01ae3d94e.js" crossorigin="anonymous"></script>

<nav>//code<nav>

<script src="script.js"></script>

为抽屉式导航栏 navbar.html 创建单独的文件

<ul>
    <li><a href="index.html">Home</a></li>
    <li><a href="contact.html">Contact</a></li>
    <li><a href="about.html">About</a></li>
    <li><a href="portfolio.html">Portfolio</a></li>
</ul>

在您的索引中。html

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

<div id="nav"></div>

在你的 script.js 添加这个

$(function() {

    $("#nav").load("navbar.html");

    function activeNav() {
        var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
         $("#nav ul li a").each(function(){
              if($(this).attr("href") == pgurl || $(this).attr("href") == '' )
              $(this).addClass("active");
         });
    }

    setTimeout(function() {
        activeNav();
    }, 100);

});

现在您可以将 script.js 文件导入其他 HTML 并让 jquery 加载导航栏。 不要忘记在要包含导航栏代码的文件中添加 id 作为导航,例如<div id="nav"></div> 参考答案

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM