首页 > 解决方案 > 一个自包含的 Javascript/Html 模块 - 这可能吗?

问题描述

[编辑:我可能找到了另一种解决方案。Kooilnc 的解决方案看起来不错。这个问题底部的解决方案比 Kooilnc 的解决方案更好还是更差?]

我有一个div相关的 javascript 代码。我想把这个的htmldiv和相关的javascript代码都放在一个文件中,一种自包含的“模块”,例如

mydiv.html

<html>
<div id="Wibble" style="display: none;">
    ... loads of structure for just this div
</div>
<script type="text/javascript">
    ... loads of js functions just associated with this div
</script>
</html>

然后在我的主页中,index.html我想以某种方式包含这个“模块”。

我发现的唯一东西是服务器端包括:

索引.html

<!DOCTYPE html>
<html>
<head>
    ... loads of stuff
</head>
<body>
   ... loads of other html structure

   <!--#include FILE="mydiv.html" -->

   ... loads of other html structure and script tags
</body>
</html>

问题1:有更好的方法吗?

问题 2:我是否应该在 mydiv.html 中有 html 标签,因为这显然会在 index.html 中放置一个不合适的 html 标签?

问题 3:如果 Q2 中的那个 html 标记不应该存在,我该如何编写 mydiv.html 文件,以便它具有 Visual Studio Code 中的所有格式和漂亮的彩色结构?


编辑:

Kooilnc 的解决方案(在答案下方)看起来不错。这是我找到的另一个解决方案。它在我的开发环境 Visual Studio Code 中工作。我需要body's中包含的 html 文件中的 javascript onload。有谁知道这个解决方案是否可以在符合我body onload要求的服务器上运行?它比 Kooilnc 的解决方案更好还是更差?

<script>在此之前,jquery 必须包含在普通标签中。

我在 index.html 中插入这段代码

<!DOCTYPE html>
<html>
<head>
    ... loads of stuff
<script type="text/javascript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">  
</head>
<body>
   ... loads of other html structure

   <div id="include_mydiv"></div>
   <script>
       $(function(){
           $("#include_mydiv").load("mydiv.html");
       });
   </script>

   ... loads of other html structure and script tags
</body>
</html>

而 mydiv.html 没有任何<html>标签:

<div id="Wibble" style="display: none;">
    ... loads of structure for just this div
</div>
<script type="text/javascript">
    ... loads of js functions just associated with this div
</script>

标签: javascriptmoduleinclude

解决方案


您可以尝试从模板元素导入。这是一个可能有用的简化模板示例。

如果您需要从外部文件导入,请查看我为您准备的这个示例。

document.querySelectorAll(`[data-import]`).forEach( el => {
  if (!el.dataset.imported) {
    el.appendChild(document.querySelector(`#${el.dataset.import}`)
      .content.cloneNode(true));
    el.dataset.imported = `ok`;
  }
});
<template id="someForm">
    <script>
      document.addEventListener(`click`, handle);
      function handle(evt) {
        if (evt.target.nodeName === `BUTTON`) {
          alert(`Yes. I am handled`);
        }
      }
    </script>
    <button id="sub">Handle me!</button>
</template>

<template id="somethingElse">
    <style type="text/css">
      .red {color: red;}
    </style>
    <p class="red">I am appended too</p>
</template>

<div data-import="someForm"></div>
<div data-import="somethingElse"></div>


推荐阅读