繁体   English   中英

未捕获的引用错误:变量未定义

[英]Uncaught Reference Error: variable undefined

我试图在单独的 javascript 文件中定义 class,然后在我的 HTML 文件中使用该 class。

这就是我正在尝试的。

  1. 我在 VoiceCard.js 文件中创建了 class VoiceCard:
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;
    }
  1. 我创建了一个 HTML 文件,并将该文件添加为源文件:
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example</title>
    <meta charset="utf-8">
    <script type="module" src="../VoiceCard.js"></script>
</head>
  1. 我创建了一个脚本,在其中调用 class 以创建 VoiceCard class 的新变量并将其中一个属性记录到控制台:
<!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。

我似乎找不到错误的原因。 任何帮助,将不胜感激。

模块不创建全局变量。 这就是他们的大部分观点。 :-)

以下是如何做您似乎想做的事情:

  1. 删除VoiceCard.jsscript标签。

  2. VoiceCard.js中,通过在 class 前面添加exportexport class

  3. 将内联脚本更改为从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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM