javascript - 一个自包含的 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>
解决方案
您可以尝试从模板元素导入。这是一个可能有用的简化模板示例。
如果您需要从外部文件导入,请查看我为您准备的这个示例。
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>
推荐阅读
- python - 使用 python 从 S3 获取最新文件并仅推送最新的日志文件
- r - 使用已知信息按顺序执行计算并在 R 中按组填充未来值
- java - 在 MPJ Express 集群模式下无法增加 Java 堆空间
- android - 尝试实现隐式意图,但它不起作用
- docker - docker容器内的gradlew包装非常慢
- c# - 当我尝试使用我的 Google 服务帐户通过 Gmail API 发送电子邮件时,“myemail@mydomain.com”的委派被拒绝
- python - 如何删除一封邮件?
- spring-boot - Fire Store 插入批量数据不一致
- c# - 使用适用于 ASP.NET 的 firebase SDK 处理登录
- postgresql - 如何释放 plpgsql 中的内存?