[英]How do I overcome a "function is not defined" error when loading an external .js file?
我想創建一個 JS 插件(使用 ES6),以便可以從 HTML 文件中調用它,如下所示:
<div id="emails-box"></div>
<script src="emails-box.js"></script>
<script>
const container = document.querySelector('#emails-box')
EmailsBox({container, ...options})
//some code
</script>
並且可以獨立使用。
EmailsBox 將做的是獲取容器並添加一個帶有盒子的子 div 來存儲一堆電子郵件。
我已經嘗試這樣做了 2-3 天,但是每次我嘗試加載 .js 文件時,我都會得到:
EmailsBox is not defined
我快絕望了你能給我一些光嗎? 謝謝!
編輯:在我的 emails-box.js 文件中,我可以有這樣的東西:
var EmailsBox = function(obj){
console.log("EmailsBox called")
// some code
return true;
}
對我來說效果很好。 確保 emails-box.js 與 index.html 位於同一文件夾中,並且名稱與您要鏈接的名稱匹配。 工作設置
很可能是 .js 文件的文件路徑被錯誤引用。 所以首先確保你正確引用了文件。 如果是,則嘗試定義函數,例如不要將其分配給變量,它可能不會在加載頁面上定義。
function EmailsBox(obj){
// some code
}
如果您真的需要將其分配給變量,請嘗試使用 ready 函數。
var EmailsBox = function(obj){ console.log("EmailsBox called") // some code return true; }
<script> (function() { EmailsBox({container, ...options}) })(); </script>
調用該函數時,請確保已定義options
變量。 所以,而不是調用:
EmailsBox({container, ...options});//when options is not defined,
首先定義選項,然后像這樣調用 EmailsBox 函數:
var options = 'hello'; //for example
EmailsBox({container, ...options});
如果您的 emails-box.js 文件被正確引用,它應該可以正常工作。
很有可能是你的源代碼有問題,但如果是因為它沒有加載這會很奇怪,那么嘗試使用 js 加載腳本,如果這肯定是錯誤的,你應該檢查它是正確的
var source = 'source here to script file';
var script = document.createElement('script');
script.onload = function () {
//what you want to do with this script
};
script.src = source();
document.head.appendChild(script);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.