繁体   English   中英

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

[英]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 函数的情况下工作的部分,所以我想我可能在那里做错了什么?

我实在想不通。 非常感谢任何帮助。

已解决,谢谢大家。 有一些错误。

  1. Lee Taylor亲切地指出。 file1.js 中不应该有 $(document).ready(function () {}) 因为它是一个函数,并且其中的每个函数都无法导出,因为它们存在于 ready 函数中。
  2. 标签中缺少的“type=module”。 这个答案

import 语句不能在嵌入式脚本中使用,除非此类脚本具有 type="module"。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM