简体   繁体   中英

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.

rates.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

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.

    <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. 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. Here is the example:

index.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

import { CAD } from './demo.js'

console.log(CAD) // CAD obj

rates.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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM