我正在嘗試在單獨的 javascript 檔案中定義一個類,然后在我的 HTML 檔案中使用該類。
這就是我正在嘗試的。
- 我在 VoiceCard.js 檔案中創建類 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;
}
- 我創建了一個 HTML 檔案,在其中將檔案添加為源:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example</title>
<meta charset="utf-8">
<script type="module" src="../VoiceCard.js"></script>
</head>
- 我創建了一個腳本,在其中呼叫類以創建 VoiceCard 類的新變數并將其中一個屬性記錄到控制臺:
<!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>
錯誤是:未捕獲的 ReferenceError:未定義 VoiceCard。
我似乎找不到錯誤的原因。任何幫助,將不勝感激。
uj5u.com熱心網友回復:
模塊不創建全域變數。這是他們的重點。:-)
以下是如何執行您似乎想要執行的操作:
洗掉 的
script標簽VoiceCard.js。在
VoiceCard.js中,通過在前面添加來匯出類。exportclass將行內腳本更改為從
VoiceCard.js檔案中匯入類的行內模塊。
所以:
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>
瀏覽器會VoiceCard.js在看到import.
uj5u.com熱心網友回復:
您可以洗掉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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/474254.html
標籤:javascript html 哎呀 参考错误
