[英]call a function func1of file1.js from func2 of file2.js file and func1 uses a global variable declared in file1.js
[英]Can I call a function from a file JavaScript from another file1.js?
我搜索了 StackOverflow 并找到了这个,但我似乎无法让它在我的 JQuery 项目中工作。 前提:当函数都在一个文件中时,代码就可以正常工作。 我必须文件:file1.js
export{hextorgb, randomColor, rgbtohex};
$(document).ready(function () {
function hextorgb(hex) {
var rgb = /^#{1}([a-f\d]{2})([a-f\d]{2})([a-f\d]{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)文件中使用它们。据我所知,导出和导入应该没问题,但它没有'不工作。file2.js 中的导入完全破坏了我的代码,即使是在没有 file1.js 函数的情况下工作的部分,所以我想我可能在那里做错了什么?
我实在想不通。 非常感谢任何帮助。
已解决,谢谢大家。 有一些错误。
import 语句不能在嵌入式脚本中使用,除非此类脚本具有 type="module"。
不幸的是,当我试图找到解决方案时,我逐渐更新了我的代码,所以你现在看到的代码正在运行,但如果有人遇到同样的问题,请尝试检查这些东西!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.