[英]How Would one fix “Uncaught ReferenceError: canv is not defined at otherfile.js:3” when canv is being imported from main.js
我正在從我的main.js文件中導出一個畫布元素對象到一個我想處理畫布對象事件的單獨文件中。 我已經在其他文件的函數中引用它之前導入了它,但是,每當我嘗試訪問畫布對象的“ onmouseup”事件時,都會在實現它的第一行給出上述錯誤。 引用確實在函數中起作用,而不是在函數外部時起作用。 該另一個文件應導入到main.js中。
我以為問題是我在定義main.js中的canv之前要在main.js中導入其他文件,因此我在導入其他文件之前先定義了canv。
像這樣
export const canv = document.getElementById('window');
import {resize} from "/scripts/otherfile.js";
resize(10,80);
這仍然給相同的錯誤,所以我徹底陷入了困境。
main.js
import {resize} from "/scripts/otherfile.js";
export const canv = document.getElementById('window');
resize(10,80);
otherfile.js
import {canv} from "../main.js";
let focus = false;
canv.onmouseenter = () => focus = true;
export const resize = (x, y) =>{
canv.height = y;
canv.width = x;
}
的HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Graphing Calculator</title>
</head>
<body>
<canvas id="window" style="border:dotted"></canvas>
<script type="module" src="main.js"></script>
</body>
</html>
otherfile.js的第3行引發錯誤。 但是,通過在另一個文件中調整大小或在main.js中調用resize不會發生錯誤
我希望其他文件能夠引用canv及其事件。 但是canv在這種情況下顯然沒有定義。
只需設置window.canv
,而不是嘗試導出canv
並重新導入它。
main.js:
window.canv = document.getElementById('window');
// other code
這允許otherfile.js
將canv
用作變量。 (可選)您可以使用const canv = window.canv
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.