我可以从文件JavaScript从另一个file1.js调用函数吗?



我通过StackOverflow搜索,我发现了这个,但我似乎不能使它在我的JQuery项目中工作。前提:当所有函数都在一个文件中时,代码就可以正常工作了。我有文件:file1.js

export{hextorgb, randomColor, rgbtohex};
$(document).ready(function () {
function hextorgb(hex) {
var rgb = /^#{1}([a-fd]{2})([a-fd]{2})([a-fd]{2})/i.exec(hex);
rgb[1] = parseInt(rgb[1], 16).toString(10);
rgb[2] = parseInt(rgb[2], 16).toString(10);
rgb[3] = parseInt(rgb[3], 16).toString(10);
return rgb;
}
function randomColor() {
var color = "#";
while (color.length < 7) {
color += Math.floor(Math.random() * 256).toString(16);
}
return color;
}
function rgbtohex(color) {
var hex = parseInt(color).toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
})

和file2.js

import {hextorgb,randomColor, rgbtohex} from "./file1.js";
$(document).ready(function () {

function generateRandomCol() {
var rgb = randomColor();
var rgbarray = hextorgb(rgb);
output(rgbarray[1], rgbarray[2], rgbarray[3]); /*where output is another function defined in this file */
$("#redslider").val(rgbarray[1]);
$("#redoutput").val(rgbarray[1]);
$("#greenslider").val(rgbarray[2]);
$("#greenoutput").val(rgbarray[2]);
$("#blueslider").val(rgbarray[3]);
$("#blueoutput").val(rgbarray[3]);
}
$("#generaterandom").click(function () {
generateRandomCol();
})
$("body").keypress(function (e) {
if (e.keyCode == 32) {
generateRandomCol();
}
})

})

我把它们放在HTML文件的头部:

<head> 
<script src="../js/file1.js" type="module"></script>
<script src="../js/file2.js" type="module"></script>
</head>

我想使用file1.js中的函数到file2.js(因为我将在其他Javascript (JQuery)文件中使用它们)。据我所知,使用exportimport应该没问题,但它不起作用。在file2.js中的导入完全破坏了我的代码,甚至没有file1.js函数工作的部分,所以我想我可能在那里做错了什么?

我真的想不明白。非常感谢您的帮助。

修复,谢谢大家。有一些错误。

  1. Lee Taylor好心指出的那个。不应该有$(document)。file1.js中的ready(function(){}),因为它是一个函数,其中的每个函数都不能导出,因为它们存在于ready函数中。
  2. 缺失的"type=module"从标签。从这个答案

import语句不能在嵌入式脚本中使用,除非该脚本具有type="模块"

  1. 一个在file1.js中的函数试图调用file2.js中的函数,但我没有从file2.js导入/导出任何函数。

不幸的是,当我试图找到解决方案时,我逐渐更新了我的代码,所以你现在看到的代码正在工作,但如果有人有同样的问题,请尝试检查这些东西!

最新更新