javascript - How do I make values update automatically if user clicks on another option?
问题描述
I currently have a currency converter which works fine, but when the user selects a different currency, I want the calculation to happen automatically without them having to press enter. I thought it would require adding an event listener for a click but I can't seem to get it to work.
I've tried setting up an event listener but I think I'm referencing the wrong things.
function init() {
const data = [
{
currency: 'btc',
we_buy: 0.58,
we_sell: 0.77,
img_path: 'img/bitcoin.svg',
icon: 'fab fa-btc'
},
{
currency: 'usd',
we_buy: 0.67,
we_sell: 0.82,
img_path: 'img/united-states.svg',
icon: 'fas fa-dollar-sign'
},
{
currency: 'gbp',
we_buy: 0.50,
we_sell: 0.68,
img_path: 'img/united-kingdom.svg',
icon: 'fas fa-pound-sign'
},
{
currency: 'eur',
we_buy: 0.59,
we_sell: 0.76,
img_path: 'img/european-union.svg',
icon: 'fas fa-euro-sign'
}
];
// Image container
const imagesContainer = document.getElementById("currencies");
imagesContainer.addEventListener('click', output_we_sell);
let selectedCurrency = null;
var selectCurrency = function (index) {
const element = data[index];
selectedCurrency = data[index];
document.getElementById("currency-selected").innerHTML = `Currency selected: ${element.currency}`;
document.getElementById("data_icon").className = element.icon;
};
(() => {
for (let i = 0; i < data.length; i++) {
imagesContainer.innerHTML += `<div class="currency" onclick=selectCurrency(${i})><img id=${i} src=${data[i].img_path}></div>`;
}
selectCurrency(0);
const amount = document.getElementById("amount");
amount.onkeyup = () => {
const output_we_buy = document.getElementById("output_we_buy");
const output_we_sell = document.getElementById("output_we_sell");
if (amount.value === '') {
output_we_buy.innerHTML = 0;
output_we_sell.innerHTML = 0;
return;
}
if (!isNaN(amount.value)) {
output_we_buy.innerHTML = `${(+amount.value * selectedCurrency.we_buy).toFixed(2)}`;
output_we_sell.innerHTML = `${(+amount.value * selectedCurrency.we_sell).toFixed(2)}`;
}
}
}
)();
}
document.addEventListener("DOMContentLoaded", init)
<div class="container-fluid">
<div class="currencies-container">
<div class="currencies" id="currencies">
</div>
<div class="currency-selected" id="currency-selected">
No currency selected.
</div>
<div class="output">
<div class="row">
<div class="input-group">
<input type="text" maxlength="5" pattern="[0-9]{4}" min="0" max="99999"class="form-control" aria-label="Amount of GP in Millions" placeholder="Amount of GP (in millions)"
id="amount">
<div class="input-group-append">
<span class="input-group-text"><i id="data_icon"></i></span>
<span class="input-group-text" id="output_we_buy">.00</span>
<span class="input-group-text" id="output_we_sell">.00</span>
</div>
</div>
</div>
</div>
</div>
</div>
I expect the script to generate a new result if the user clicks another currency, rather than having to press enter.
解决方案
In your code, you've stored anonymous function inside the value amount.onkeyup()
at the bottom, outside the scope of selectCurrency()
, so selectCurrency()
cannot access it. You'll want to raise the scope, and then use it in the places you want.
// made function originally in amount.onkeyup have a greater scope
const calculate = () => {
const output_we_buy = document.getElementById("output_we_buy");
const output_we_sell = document.getElementById("output_we_sell");
if (amount.value === '') {
output_we_buy.innerHTML = 0;
output_we_sell.innerHTML = 0;
return;
}
if (!isNaN(amount.value)) {
output_we_buy.innerHTML = `${(+amount.value * selectedCurrency.we_buy).toFixed(2)}`;
output_we_sell.innerHTML = `${(+amount.value * selectedCurrency.we_sell).toFixed(2)}`;
}
}
// ...
var selectCurrency = function (index) {
const element = data[index];
selectedCurrency = data[index];
document.getElementById("currency-selected").innerHTML = `Currency selected: ${element.currency}`;
document.getElementById("data_icon").className = element.icon;
calculate(); // Added calculate here
};
// ...
(() => {
for (let i = 0; i < data.length; i++) {
imagesContainer.innerHTML += `<div class="currency" onclick=selectCurrency(${i})><img id=${i} src=${data[i].img_path}></div>`;
}
selectCurrency(0);
const amount = document.getElementById("amount");
amount.onkeyup = calculate; // Changed this to use the calculate function
}
推荐阅读
- git - 如何从旧的 Git 提交中删除大文件?
- python - 如何使用 txt 文件交叉检查列表
- python - ImportError:无法导入名称“解析器”
- python - 有没有办法在不选择元素的情况下点击 Selenium(python)?
- python - 使用 pygame 生成玩家精灵图像的问题
- sql-server - If then else 带有变量和更新表
- android - Android 主项目 build.gradle 中的插件部分和缺少的模块
- android - 使用Android如何获取Java文件的最后修改时间戳?
- python - BeautifulSoup 和 Craiglist - 无法获取具有相同属性和结构的数据
- java - 如何使用firebase中的网站用户注册详细信息通过android应用登录用户?