[英]Uncaught Reference Error: variable undefined
我试图在单独的 javascript 文件中定义 class,然后在我的 HTML 文件中使用该 class。
这就是我正在尝试的。
class VoiceCard {
constructor(nickname, date_time, post_title, voice_post) {
this.nickname = nickname;
this.date_time = date_time;
this.post_title = post_title;
this.voice_post = voice_post;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example</title>
<meta charset="utf-8">
<script type="module" src="../VoiceCard.js"></script>
</head>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example</title>
<meta charset="utf-8">
<script type="module" src="../VoiceCard.js"></script>
</head>
<body>
<script type="text/javascript">
let v_card = new VoiceCard(
"Lorder",
"12:00",
"First Voicer Post",
"file_location.mp4");
console.log(v_card.nickname);
</script>
</body>
</html>
错误是:Uncaught ReferenceError: VoiceCard is not defined。
我似乎找不到错误的原因。 任何帮助,将不胜感激。
模块不创建全局变量。 这就是他们的大部分观点。 :-)
以下是如何做您似乎想做的事情:
删除VoiceCard.js
的script
标签。
在VoiceCard.js
中,通过在 class 前面添加export来export
class
。
将内联脚本更改为从VoiceCard.js
文件导入 class 的内联模块。
所以:
export class VoiceCard {
// ^^^
constructor(nickname, date_time, post_title, voice_post) {
this.nickname = nickname;
this.date_time = date_time;
this.post_title = post_title;
this.voice_post = voice_post;
}
} // <== This closing `}` was missing
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example</title>
<meta charset="utf-8">
<!-- No script tag for VoiceCard -->
</head>
<body>
<script type="module">
import { VoiceCard } from "../VoiceCard.js"; // ***
let v_card = new VoiceCard(
"Lorder",
"12:00",
"First Voicer Post",
"file_location.mp4"
);
console.log(v_card.nickname);
</script>
</body>
</html>
浏览器会在看到import
时自动下载VoiceCard.js
。
您可以删除type="module"
来解决这个问题
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example</title>
<meta charset="utf-8">
<script src="../VoiceCard.js"></script>
</head>
<body>
<script type="text/javascript">
let v_card = new VoiceCard(
"Lorder",
"12:00",
"First Voicer Post",
"file_location.mp4");
console.log(v_card.nickname);
</script>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.