首页 > 解决方案 > 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.

标签: javascripthtml

解决方案


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
}

推荐阅读