我正在学习 JavaScript 以及 HTML 和 CSS。我编写了 JavaScript 文件 Primes.js,其中包含一些用于测试的素数查找相关函数。
为了使用外部 .js 文件进行测试,我编写了以下 HTML 文件:
...
<body>
<script src="Primes.js">
console.log("Loaded...");
var n = 13;
alert(n + " is prime?: " + isPrime(n));
console.log("Ending...");
</script>
</body>
...
但它从未执行脚本 block 内的语句。
环顾四周,我发现this answer ,并将正文更改为:
...
<body>
<script src="Primes.js"></script>
<script>
console.log("Loaded...");
var n = 13;
alert(n + " is prime?: " + isPrime(n));
console.log("Ending...");
</script>
</body>
...
神奇的是,它按预期工作了。需要空脚本标签来导入文件似乎很奇怪。
为什么要求导入.js文件的脚本标签为空?如果脚本是其使用的同一标签中的源,是否会产生后果?
最佳答案
如 w3c 中所写当 src
属性存在时,脚本内的内容应该用于脚本的文档。
If a script element's src attribute is specified, then the contents of the script element, if any, must be such that the value of the text IDL attribute, which is derived from the element's contents, matches the documentation production in the following ABNF, the character set for which is Unicode.
关于javascript - 为什么导入JS文件时script标签需要留空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34030228/