javascript - 如何使用另一个 .js 文件中的函数?

标签 javascript jquery function getscript

这是我的代码的简化:

// script1.js
$(document).ready(function(){
    .
    .
    function myfunc(){ ... }
    .
    .
});


// script2.js
$(document).ready(function(){
    .
    .
    //doesn't work
    $.getScript("./script1.js");
    // anyway I need to call myfunc() here ... how can I access it?
    .
    .
});

如您所见,我使用了 $.getScript() 来请求 script1.js 文件,但仍然使用 myfunc()那里没有定义。我该如何处理?

最佳答案

As you can see, I've used $.getScript() to require sccript1.js file, but still myfunc() is not defined there. How can I handle that?

myfunc 是在 document.ready 事件中定义的,并且未全局公开,因此您无法在另一个事件中使用相同的内容不在此文档就绪事件内部的函数。

您需要 全局导出此函数 在 document.ready 事件之外定义它

全局导出功能

$(document).ready(function(){
    .
    .
    function myfunc(){ ... }
    window.myfunc = myfunc; //this line added here
    .
    .
});

或者在外部定义

$(document).ready(function(){
    .
    .

    .
    .
});
function myfunc(){ ... }

关于javascript - 如何使用另一个 .js 文件中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47967763/

相关文章:

javascript - 基于出生日期的 EOFY 年龄

javascript - 将数组从 Javascript 传递到 asp.net

jquery - CSS/jQuery 库来近似 Google News UI 的外观和感觉?

C++:我正在解决一个问题,突然我注意到编译的代码没有返回语句

javascript - AngularJS 不重新加载部分 jQuery 脚本

javascript - 如何在 d3 文本函数中返回 html?

javascript - 使用 d3.js 在 map 上创建工具提示

JQuery:以编程方式添加的 anchor 与我的点击功能无关

javascript - 浏览器中出现错误,提示找不到变量?

javascript - 将方法应用于javascript中的对象和私有(private)变量