A self contained Javascript/Html module – Is this possible?

8,728次阅读
没有评论

共计 2059 个字符,预计需要花费 6 分钟才能阅读完成。

题意 :一个自包含的 JavaScript/HTML 模块 – 这可能吗?

问题背景:

[EDIT: I have possibly found another solution. Kooilnc’s solution looks good. Is the solution at the bottom of this question better or worse than Kooilnc’s?]

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

I have a div with associated javascript code. I would like to have the html for just this div and the associated javascript code all in one file, a kind of self contained ‘module’, eg

我有一个 div 和相关的 JavaScript 代码。我希望将这个 div 的 HTML 和相关的 JavaScript 代码都放在一个文件中,形成一种自包含的“模块”,例如:

mydiv.html





Then in my main page index.html I would like to include this ‘module’ in some way.

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

The only thing I have found is a Server Side Include:

我找到的唯一方法是服务器端包含:

index.html




    ... loads of stuff


   ... loads of other html structure

   

   ... loads of other html structure and script tags


Question 1: Is there a better way of doing this?   问题 1:有没有更好的方法来做到这一点?

Question 2: Should I have the html tag in mydiv.html as that will obviously put an html tag in index.html which is out of place?

问题 2:我应该在 mydiv.html 中包含 html 标签吗?因为这显然会在 index.html 中放入一个不合适的 html 标签。

Question 3: If that html tag in Q2 should not be there, how do I write the mydiv.html file so it has all the formatting and nice coloured structure in Visual Studio Code?

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


Edit:

Kooilnc’s solution (below in the answers) looks good. Here is another solution I have found. It is working in my development environment Visual Studio Code. I need the javascript in my included html file in body‘s onload. Does anyone know if this solution will work on a server with my body onload requirement? Is it better or worse than Kooilnc’s solution?

Kooilnc 的解决方案(在下面的回答中)看起来不错。这里是我找到的另一种解决方案。它在我的开发环境 Visual Studio Code 中有效。我需要在包含的 html 文件中的 `body` 的 `onload` 中运行 javascript。有没有人知道这个解决方案是否能满足我对服务器的 `body onload` 要求?它比 Kooilnc 的解决方案更好还是更差?

Jquery must be included with the normal  tag prior to this.

jQuery 必须在此之前使用普通的 `

I insert this code within index.html

我将此代码插入到 `index.html` 中。




    ... loads of stuff

… loads of other html structure and script tags

原文地址: A self contained Javascript/Html module – Is this possible?

    正文完
     0
    Yojack
    版权声明:本篇文章由 Yojack 于2024-11-10发表,共计2059字。
    转载说明:
    1 本网站名称:优杰开发笔记
    2 本站永久网址:https://yojack.cn
    3 本网站的文章部分内容可能来源于网络,仅供大家学习与参考,如有侵权,请联系站长进行删除处理。
    4 本站一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
    5 本站所有内容均可转载及分享, 但请注明出处
    6 我们始终尊重原创作者的版权,所有文章在发布时,均尽可能注明出处与作者。
    7 站长邮箱:laylwenl@gmail.com
    评论(没有评论)