我需要从某个包含 3 个类的 javascript 文件创建类的实例,并从另一个 javascript 文件调用该类的方法。主 javascript 文件中的类如下:
function Class1(param1, param2) {
this.openTag;
this.closeTag;
this.htmlTags;
this.openTag = '<div id="' + this.elementId + '">';
this.closeTag = '</div>';
this.htmlTags = {
sectionTitle: {
openTag: '<h2 class="class1">',
closeTag: '</h2>'
},
group: {
openTag: '<div class="class2">',
closeTag: '</div>'
},
table: {
openTag: '<table class="class3">',
closeTag: '</table>'
}
}
...
}
以及类似的方法:
Class1.prototype.someName = function (index) {
var outputHtml = '';
var text = this.tableHeaders[index] || '';
outputHtml += '<th>' + text + '</th>';
return outputHtml;
}
如何创建这些类的实例并从另一个 javascript 文件调用它们,或者如何在 HTML 中使用它们?当我尝试执行 ES6 导入/导出或创建引用这些类的新对象时,它会出现以下错误:
从源“null”访问“file:///Users/user/Desktop/project/someName.js”处的脚本已被 CORS 策略阻止:仅协议(protocol)方案支持跨源请求: http、数据、chrome、chrome 扩展、https。
&
app.js:1 未捕获的语法错误:无法在模块外部使用 import 语句
最佳答案
所以,我解决了我的问题。我没有使用node.js
。我试图从另一个文件调用这些函数并将它们显示在 HTML
文件中。但 CORS 政策不允许我使用它们。我所做的是,安装Live Server VS Code 的扩展。
它启动了一个localhost
服务器,问题就解决了。因为你需要的是http://
。因为当您打开 HTML 文件时,它将从 file://
加载模型,这会导致问题。您只需打开一个 HTML 文件并右键单击编辑器并单击使用 Live Server 打开
即可启动 localhost
。
我使用了诸如 const abc = new Class();
和 abc.someMethod();
之类的实例。
重要说明
不要忘记将 script
标记添加到您的 HTML
中,并确保您的主 script
标记位于其他标记下方,例如:
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="./readyFunctions.js"></script> <!-- Functions you will call -->
<script src="./main.js"></script> <!-- js file where you call functions -->
另一个重要的注意事项是,如果即使您按照我的指示操作也遇到了此类错误,请确保您的 script
标记没有 type= "module"
.
您还可以查看this post对于其他类型的解决方案。希望它有帮助:)
关于Javascript 导入/导出 CORS 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58261139/