【问题标题】:Import JavaScript function into html [duplicate]将 JavaScript 函数导入 html [重复]
【发布时间】:2023-02-02 22:59:59
【问题描述】:

如何将我的函数从 JavaScript 文件导入到 html 中以便在 html 脚本中进一步使用?

JavaScript 文件:

export function test() {
    console.log('test');
}

网页文件:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script type="module" src = "script.js">
    test();    
  </script>
</head>

<body>
</body>

</html>

【问题讨论】:

  • 您需要在主脚本中导入。请注意,JS 模块只能在 Web 服务器上工作,它们不能在本地工作

标签: javascript html function import


【解决方案1】:

这样导入

<script type="module">

import { test } from "./script.js";

test();

</script>

【讨论】:

    【解决方案2】:

    如果你使用

    <script>
    
    </script>
    

    并将你的 JavaScript 置于两者之间

    【讨论】:

      猜你喜欢
      • 2020-04-27
      • 2021-01-10
      • 2017-08-26
      • 2011-08-19
      • 1970-01-01
      • 1970-01-01
      • 2019-01-24
      • 2020-07-05
      • 2018-03-03
      相关资源
      最近更新 更多