我有一个关于在 javascript 中包含文件的问题。
我有一个非常简单的例子:
--> index.html
--> models
--> course.js
--> student.js
课程.js:
function Course() {
this.id = '';
this.name = '';
}
学生拥有课程财产。像这样:
import './course';
function Student() {
this.firstName = '';
this.lastName = '';
this.course = new Course();
}
和index.html是这样的:
<html>
<head>
<script src="./models/student.js" type="text/javascript"></script>
</head>
<body>
<div id="myDiv">
</div>
<script>
window.onload= function() {
var x = new Student();
x.course.id = 1;
document.getElementById('myDiv').innerHTML = x.course.id;
}
</script>
</body>
</html>
但我在“var x = new Student();”行上收到错误:
学生未定义
当我从 Student 中删除导入时,我不再收到错误。
我尝试过使用(要求、导入、包含、创建自定义函数、导出),但没有一个对我有用。
有人知道为什么吗?以及如何解决这个问题?
附:路径是正确的,它来自 VS Code 中的自动完成
以下内容适用于我的 Firefox 和 Chrome。在 Firefox 中,它甚至可以从file:///
模型/course.js
export function Course() {
this.id = '';
this.name = '';
};
模型/student.js
import { Course } from './course.js';
export function Student() {
this.firstName = '';
this.lastName = '';
this.course = new Course();
};
索引.html
<div id="myDiv">
</div>
<script type="module">
import { Student } from './models/student.js';
window.onload = function () {
var x = new Student();
x.course.id = 1;
document.getElementById('myDiv').innerHTML = x.course.id;
}
</script>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)