发生这种情况是因为
我已经尝试了一段时间,但似乎无法让我的新手理解这一点。我可以安慰log硬币,但似乎无法让它与"相乘;btcnumber’输入,然后更新。innerText
const api_url = "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin%2Cethereum%2Cbinancecoin%2Ccardano%2Csolana%2Cterra-luna&vs_currencies=usd";
async function getData() {
const response = await fetch(api_url);
const data = await response.json();
console.log(data.bitcoin.usd);
}
getData();
function coinValue() {
let bitcoin = parseInt(document.getElementById("btcnumber") * (data.bitcoin.usd));
document.getElementById("c-v").innerText = bitcoin.toFixed(8);
}
document.addEventListener("DOMContentLoaded", function() {
let submit = document.getElementById("calculateButton");
calculateButton.addEventListener("click", function() {
coinValue()
})
})
<input id="btcnumber" type="number" class="form-control" placeholder="Number Purchased">
<button id="calculateButton" onclick=coinValue()>Calculate</button>
<h4>CURRENT VALUE <span id="c-v"></span></h4>
coinValue()
函数中不存在data
变量。将其放在函数之外,使其成为全局变量。
此外,在coinValue()
函数中,您必须在乘法结束时将.value
相加,以获得输入的实际值。
let data;
const api_url = "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin%2Cethereum%2Cbinancecoin%2Ccardano%2Csolana%2Cterra-luna&vs_currencies=usd";
async function getData() {
const response = await fetch(api_url);
data = await response.json();
console.log(data.bitcoin.usd);
}
getData();
function coinValue() {
let bitcoin = parseInt(document.getElementById("btcnumber").value * (data.bitcoin.usd));
document.getElementById("c-v").innerText = bitcoin.toFixed(8);
}
document.addEventListener("DOMContentLoaded", function() {
let submit = document.getElementById("calculateButton");
calculateButton.addEventListener("click", function() {
coinValue()
})
})
<input id="btcnumber" type="number" class="form-control" placeholder="Number Purchased">
<button id="calculateButton" onclick=coinValue()>Calculate</button>
<h4>CURRENT VALUE <span id="c-v"></span></h4>