Выборка JavaScript API не работает при первой загрузке - PullRequest
0 голосов
/ 19 сентября 2019

Я работаю над этим приложением для конвертации валюты и выбираю API из https://exchangeratesapi.io/

Приложение работает, за исключением того, что оно только загружает API при обновлении.Я использую onload в теге body.

Есть идеи, как заставить его работать при первой загрузке без обновления?

Заранее спасибо

<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>JS Bin</title>

        <script type="text/javascript" src="indexCurrencyFirst.js" ></script>
        <script type="text/javascript" src="indexCurrency.js" ></script>
        <link rel="stylesheet" type="text/css" href="styleCurrency.css">  

</head>
<body onload="convertCurrencyRight()" >

    <nav>
      <ul class="navbar">
        <li id="logo"><img src="Assets/Logo_openCurren.svg"></li> 
        <li id="date">Fecha</li>
      </ul>
    </nav>
    <div class="wrapper" >
        <div id="containerFrom">
          <input id="fromQuantity" type="number" value="1" onchange="convertCurrencyRight()" onkeyup="convertCurrencyRight()"/>
          <select id="from" onchange="convertCurrencyRight()" onkeyup="convertCurrencyRight()">


          </select>
         </div>   
         <div id="arrow"><img src="Assets/Arrow.svg"> </div>

        <div id="containerTo"> 
         <input id="toQuantity" type="number" value="0" onchange="convertCurrencyLeft()" onkeyup="convertCurrencyLeft()"/>
          <select id="to"  onchange="convertCurrencyRight()" onkeyup="convertCurrencyRight()">
            <option value="EUR"  selected>EUR</option>
          </select>
        </div>
    </div>    

    <div class="wrapper"  >
        <div id="containerCValues">
            <p id="currentRateA"> 1 Eur = 0.89 Gbp  </p>
            <p id="currentRateB"> 1 Gbp = 1.12 Eur  </p>
        </div>
    </div>


</body>
</html>

Мои файлы JS

Загружены в head indexCurrencyFirst

//fill the select options with the available currencies      

fetch("https://api.exchangeratesapi.io/latest?base=")
      .then((resp) => resp.json())
      .then(function(data){
        var allRates = data.rates;
        var selectA = document.getElementById("from");
         var selectB = document.getElementById("to");
         allRates = Object.entries(allRates)


         for(var i = 0; i < allRates.length; i++) {
            var opt = allRates[i][0];
            var el = document.createElement("option");
            el.textContent = opt;
            el.value = opt;
             if(opt==="GBP"){
                 var selectedAtt=document.createAttribute("selected");
                 el.setAttributeNode(selectedAtt);
             }
            selectA.appendChild(el);

            var la = document.createElement("option");
             la.textContent = opt;
             la.value = opt;
             selectB.appendChild(la);
        }   

        })

        .catch(function(error) {
        console.log(error);
        });

и функции, которые преобразуют ставки

function convertCurrencyRight() {
    var fromCurrency = document.getElementById("from").value;
    var toCurrency = document.getElementById("to").value;
    console.log(toCurrency);

    fetch("https://api.exchangeratesapi.io/latest?base=" + fromCurrency)
      .then((resp) => resp.json())
      .then(function(data){
        //if both currencies are the same return identical values
        (fromCurrency===toCurrency) ? 
        (document.getElementById("toQuantity").value = document.getElementById("fromQuantity").value,
        document.getElementById("currentRateA").textContent= "1 " + fromCurrency + " = " + "...",
        document.getElementById("currentRateB").textContent= "")
        :
        //otherwise return the top value as the multiplication of top currency rate by the amount specied below
        (document.getElementById("toQuantity").value = (data.rates[toCurrency]*document.getElementById("fromQuantity").value).toFixed(3),
        //change the single amount values
        document.getElementById("currentRateA").textContent= "1 " + fromCurrency + " = " + (data.rates[toCurrency]).toFixed(6) + " " + toCurrency,
        document.getElementById("currentRateB").textContent= "1 " + toCurrency + " = " + (1/data.rates[toCurrency]).toFixed(6) + " " + fromCurrency)
        //load the date of the current rates
        var date = document.getElementById("date");
        date.innerHTML = "LAST UPDATED " +
        data.date.split("-").reverse().join("-");


        })

        .catch(function(error) {
        console.log(error);
        });
}


function convertCurrencyLeft() {
    ...
}

Любая идея, как это исправить.Я попытался использовать jQuery с готовым документом вместо загрузки с удачей

1 Ответ

0 голосов
/ 19 сентября 2019

Я бы просто использовал onload на вашем теге body и просто пошел с Jquery $(document).ready() и поместил ваш вызов в `convertCurrencyRight () там.В моей скрипке это работает нормально.

$(document).ready(function() {
    convertCurrencyRight();
});
...