[英]Printing a HTML + JavaScript variable from an external js to an index.html file using fetch + node.js
[英]external .js not working after using “parcel index.html”
所以我有这个我正在尝试制作的网站,我只是一遍又一遍地遇到同样的错误。 当我双击我的 index.html 时,下面的所有代码都可以正常工作,但是如果我在控制台中使用“parcel index.html”,它会显示“Uncaught ReferenceError: test is not defined”。 HTML是:
<!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>Learn Ambivalendrish</title>
<link rel="stylesheet" href="/style/index.scss">
<script src="js/script.js"></script>
</head>
<body>
<h1 onclick="test()">This is a header for testing purpose</h1>
</body>
</html>
我的js是:
function test(){
alert('test alert')
}
我已经尝试过
export function test(){
alert('test alert')
}
和
let test = () =>{
alert('test alert')
}
模块捆绑器希望脚本成为程序的入口点。
您的问题是您希望脚本创建一个全局变量,然后从外部读取该全局变量。
捆绑器不希望这样,所以当它重写您的脚本时,它不会注意确保它创建一个具有该名称的全局变量。
重写您的代码,使脚本成为入口点。
不要使用内部事件属性,使用addEventListener
绑定事件处理程序。
addEventListener('DOMContentLoaded' () => {
const heading = document.querySelector('h1');
heading.addEventListener(test);
});
旁白:标题并非设计为交互式控件。 默认情况下:它们不会对经过它们的鼠标做出反应。 它们看起来不像你可以点击的东西。 屏幕阅读器不会宣布它们是交互式的。 你不能点击他们。 如果你想要点击某些东西来触发 JS,请使用<button>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.