簡體   English   中英

如何使用另一個.js文件中的函數?

[英]How can I use a function which is into another .js file?

這是我的代碼的簡化:

// 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()來要求sccript1.js文件,但仍未在那里定義myfunc() 我該怎么處理?

正如您所看到的,我使用$ .getScript()來要求sccript1.js文件,但仍未在那里定義myfunc()。 我該怎么處理?

myfuncdocument.ready事件中定義,並且不會全局公開 ,因此您無法在另一個不在此文檔就緒事件中的函數中使用它。

你需要 全局導出此函數 定義它的document.ready事件之外

全球出口功能

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

或者在外面定義它

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

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

嘗試:

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


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

//util.js

var test = (function (){
return {
myfunc : function (){ ... }
}
})();

// script1.js

$(document).ready(function(){
  test.myfunc();
});

// script2.js

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

在您的HTML中,您應該下訂單

<script src="util.js"></script>
<script src="script1.js"></script>
<script src="script2.js"></script>

嘗試使用絕對路徑。 例如https://example.com/js/script1.js而不是./script1.js

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM