簡體   English   中英

通過 JavaScript 或 jquery 在 HTML 中動態包含文件

[英]Include file In HTML by JavaScript or jquery dynamically

我嘗試了以下代碼。 但它不能正常工作。 只有一個文件重復添加/包含。 我該如何解決這個問題? **我想創建一個自定義標簽“”,它可以包含 html 文件!!!! ——

 var createIncludeTag = document.createElement('include'); $(function(){ var includeFile = $('include').attr('href'); $("include").load(includeFile); });
 <include href="nav.html"></include> <include href="main.html"></include> <include href="footer.html"></include>

<include>不是有效的html元素。

您可以使用rel屬性設置為"import" <link>元素將資源加載到document <link>元素的load事件中,您可以使用link.import獲取資源的內容

<link rel="import" href="nav.html" type="text/html">

   $(function() {
     $("body").append($("link[href='nav.html']")[0].import.body.innerHTML)
   })

   $("link[href='nav.html']").on("load", function() {
     $("body").append(this.import.body.innerHTML)
   })

或者,您可以使用.load()

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

根據.attr() 函數的 jquery API 參考

描述:獲取匹配元素集中第一個元素的屬性值。

這就是為什么您只為所有三個元素加載第一個包含 html。

您必須改用.each()函數。

<!DOCTYPE html>
<html>

<head>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(function () {
            $("include").each(function (index, value) {
                $(this).load($(this).attr("href"));
            });
        });
    </script>
</head>

<body>
    <include href="nav.html"></include>
    <include href="main.html"></include>
    <include href="footer.html"></include>
</body>

</html>

順便說一句,創建自定義 <include> 標簽可能不是一個好主意。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM