[英]Referencing variable from one javascript file in another
I have two JS files where I would like to access the variable associated with my JS Object.我有两个 JS 文件,我想在其中访问与我的 JS Object 关联的变量。
rates.js rate.js
var CAD = {
USD : 1.2727,
EUR : 1.54,
CNY : 0.20,
BTC : 45139.58
CZK : 0.059,
GBP : 1.7338,
CHF : 1.4345,
JPY : 0.0123,
AUD : 0.9827,
PLN : 0.3405,
ZAR : 0.0839
}
var CHF = {
USD : 0.8911,
EUR : 1.0766,
CNY : 0.14,
BTC : 32154.03,
CZK : 0.041,
GBP : 1.2086,
CHF : 1,
JPY : 0.0086,
AUD : 0.685,
PLN : 0.2375,
ZAR : 0.0584
}
Second file where I would like to store a value in a variable:我想在变量中存储值的第二个文件:
dropdown.js下拉.js
if(getTicker == "AUDCAD" ){
var price = CAD.USD;
alert(price);
}
I have used the following lines in my html file in an effort to connect the two with no success.我在 html 文件中使用了以下几行,试图将两者连接起来,但没有成功。
<script src="rates.js"></script>
<script src="dropdown.js"></script>
</body>
</html>
I am not using a server therefore I cannot make modules to import and export.我没有使用服务器,因此我无法制作模块来导入和导出。 Are there any other recommendations?
还有其他建议吗?
There is a type
attribute in script
tag. script
标签中有一个type
属性。 So you can set type
as module
in your dropdown.js
file and export CAD & CHF
from rates.js
file and use them how you want.因此,您可以在
dropdown.js
文件中将type
设置为module
,并从rates.js
文件中导出CAD & CHF
,然后按照您的需要使用它们。 Here is the example:这是示例:
index.html索引.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="module" src="./dropdown.js"></script>
</body>
</html>
dropdown.js下拉.js
import { CAD } from './demo.js'
console.log(CAD) // CAD obj
rates.js rate.js
const CAD = {
USD: 1.2727,
EUR: 1.54,
CNY: 0.2,
BTC: 45139.58,
CZK: 0.059,
GBP: 1.7338,
CHF: 1.4345,
JPY: 0.0123,
AUD: 0.9827,
PLN: 0.3405,
ZAR: 0.0839,
}
const CHF = {
USD: 0.8911,
EUR: 1.0766,
CNY: 0.14,
BTC: 32154.03,
CZK: 0.041,
GBP: 1.2086,
CHF: 1,
JPY: 0.0086,
AUD: 0.685,
PLN: 0.2375,
ZAR: 0.0584,
}
export { CAD, CHF }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.