自包含的 Javascript/Html 模块 - 这可能吗?

问题描述 投票:0回答:2

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

我有一个

div
以及相关的 javascript 代码。我想要这个
div
的 html 和相关的 javascript 代码都在 one 文件中,一种自包含的“模块”,例如

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
我想以某种方式包含这个“模块”。

我唯一发现的是服务器端包含:

index.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
onload
中包含的 html 文件中的 javascript。有谁知道这个解决方案是否适用于满足我的
body
onload
要求的服务器?它比 Kooilnc 的解决方案更好还是更差?

在此之前,Jquery 必须包含在正常的

<script>
标记中。

我将此代码插入到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>
javascript module include
2个回答
2
投票

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

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

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>


-2
投票

使用 Iframe

<iframe id="inlineFrameExample"
    width="300"
    height="200"
    src="mydiv.html">

参见 https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe

© www.soinside.com 2019 - 2024. All rights reserved.