如果用户单击其他选项,我在哪里添加eventListener来更新我的应用程序

时间:2019-06-08 02:14:22

标签: javascript

当前,用户可以输入所需的金额,它将转换为适当的货币,但是如果用户单击图像并选择其他货币,我希望转换器自动更新。

我尝试为selectCurrency创建一个事件侦听器,但是图像消失了,所以我认为这是错误的方向。

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'
    }
];
const imagesContainer = document.getElementById("currencies");
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)}`;
        }
    }
}
)();

用户应该能够在输入框中输入金额,然后单击上方的另一种货币。选择货币后,转换率应立即更新。

0 个答案:

没有答案