【问题标题】:Unable to use function imported from js file without extra <script> tags无法使用从 js 文件导入的函数,没有额外的 <script> 标签
【发布时间】:2021-03-01 21:29:58
【问题描述】:

我正在尝试使用另一个 js 文件中定义的函数。

文件结构为:

main.html
js/
  util.js

以下运行正常:

main.html 是:

<html>
  <head>
    <script type="text/javascript" src="js/util.js"</script> 
    <script></script>
  </head>
  <body></body>

<script type="text/javascript">

const out = first([1, 2, 3, 4])
console.log(out)

</script>

</html>

util.js 是:

alert("in util.js")

var first = function(arr) {
  return arr[0]
}

当我从 main.html 中省略第 4 行 (&lt;script&gt;&lt;/script&gt;) 时,我会收到“in util.js”警报。但是,first 的输出没有记录。

我偶然发现了包含额外的脚本标签对的解决方案,我不清楚为什么它应该是必要的。另外,我在网上没有找到任何包含这行的例子。

鉴于此,我想知道 (A) 为什么 main.html 第 3 行不足以单独获取 first,以及 (B) main.html 第 4 行是否是首选解决方案(再次,我怀疑它不是)。

任何指针表示赞赏!

编辑:愚蠢的错字是问题所在。缺少一个“>”...

【问题讨论】:

  • 看看你上面的sn-p中的颜色编码。它给你一个线索。您在"js/util.js" 之后缺少&gt;,因此最终会从下面的行中选择结束标签。

标签: javascript html import


【解决方案1】:

Keith 在评论中回答。

问题是一个基本的错字(缺少“>”)。第 3 行应如下所示:

<script type="text/javascript" src="js/util.js"></script> 

那么,第 4 行就不需要了。

【讨论】:

    猜你喜欢
    • 2011-04-21
    • 2021-09-23
    • 2020-07-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-03
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    相关资源
    最近更新 更多