如何在 100 多个网页的网站中使用 JavaScript 组件实现 HTML

我有一个包含 200 多个网页的网站,其中包含一个导航栏(标题)。我怎样才能自动化它,所以我不必担心使用 JavaScript 更改所有 200 多个网页中的标题。实现这一目标的最佳方法是什么?


我已经使用 jQuery 实现如下,但导航栏没有显示。


    <link rel="stylesheet" href="../../assets/vendor/cubeportfolio/css/cubeportfolio.min.css">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"

        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">


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

        <script>

            $(function () {

                    $("#includedContent").load("../../html/home/header.html");

            });

        </script>


    <!-- CSS Front Template -->

    <link rel="stylesheet" href="../../assets/css/theme.css">


    <!-- CSS Front Doc -->

    <link rel="stylesheet" href="../../documentation/assets/css/starter.css">


</head>


<body>

    <!-- ========== HEADER ========== -->

    <header id="includedContent"></header>

    <!-- ========== END HEADER ========== -->


慕森王
浏览 116回答 2
2回答

交互式爱情

您已将此问题标记为 PHP 和 JS,因此我强烈建议您在 PHP(或您可能正在使用的任何其他服务器端语言)中执行某种常见的包含,而不是尝试这样做客户端(如 smootok 所示)主要是因为它会更加可靠,但也因为它在客户端上也会更快。例如:&nbsp;<?php include("includes/header.php");?>

手掌心

你可以用你想要的内容创建一个新的文件头,然后使用w3-include-html属性包含它例子<div w3-include-html="header.html"></div>添加javascript<script>function includeHTML() {&nbsp; var z, i, elmnt, file, xhttp;&nbsp; /* Loop through a collection of all HTML elements: */&nbsp; z = document.getElementsByTagName("*");&nbsp; for (i = 0; i < z.length; i++) {&nbsp; &nbsp; elmnt = z[i];&nbsp; &nbsp; /*search for elements with a certain atrribute:*/&nbsp; &nbsp; file = elmnt.getAttribute("w3-include-html");&nbsp; &nbsp; if (file) {&nbsp; &nbsp; &nbsp; /* Make an HTTP request using the attribute value as the file name: */&nbsp; &nbsp; &nbsp; xhttp = new XMLHttpRequest();&nbsp; &nbsp; &nbsp; xhttp.onreadystatechange = function() {&nbsp; &nbsp; &nbsp; &nbsp; if (this.readyState == 4) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (this.status == 200) {elmnt.innerHTML = this.responseText;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (this.status == 404) {elmnt.innerHTML = "Page not found.";}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; /* Remove the attribute, and call this function once more: */&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; elmnt.removeAttribute("w3-include-html");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; includeHTML();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; xhttp.open("GET", file, true);&nbsp; &nbsp; &nbsp; xhttp.send();&nbsp; &nbsp; &nbsp; /* Exit the function: */&nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; }&nbsp; }}</script>在页面底部调用 includeHTML() :<script>includeHTML();</script>参考:https : //www.w3schools.com/howto/howto_html_include.asp
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript