如何在JS事件间传递值?以货币转换器项目为例
解决货币转换器中
getRates()传参问题 问题核心
你需要在select的change事件中保存选中的货币值,然后在按钮点击时将这些值传入getRates(),让Promise.all()能正确获取两种货币的汇率。
解决步骤
- 存储选中的货币值:在
controlFlag的change事件回调里,把选中的货币值存在全局变量(或DOM元素的dataset属性)中,方便后续点击事件获取。 - 点击时获取参数并调用
getRates():在按钮点击事件中,取出之前存储的两个货币值,作为参数传入getRates(),再放入Promise.all()中执行。
修改后的完整代码
// 定义全局变量存储选中的货币 let selectedCurrency1 = 'pln'; let selectedCurrency2 = 'eur'; // 可根据需求调整默认值 const select1 = document.getElementById('selector1'); const select2 = document.getElementById('selector2'); const conversionButton = document.getElementById('conversionButton'); // 确保获取按钮元素 const valueForInput = document.getElementById('valueForInput'); const outputRatio = document.getElementById('outputRatio'); function controlFlag(element, flagId, currencyType) { // 初始化默认国旗与货币值 const initialValue = element.value; const initialApiUrl = 'https://www.countryflagicons.com/FLAT/64/' + initialValue + '.png'; document.getElementById(flagId).src = initialApiUrl; // 存储初始货币值 currencyType === 'first' ? selectedCurrency1 = initialValue : selectedCurrency2 = initialValue; element.addEventListener('change', function () { const selectedCountry = element.value; const apiUrl = 'https://www.countryflagicons.com/FLAT/64/' + selectedCountry + '.png'; const flagImage = document.getElementById(flagId); flagImage.src = apiUrl; // 更新存储的货币值 currencyType === 'first' ? selectedCurrency1 = selectedCountry : selectedCurrency2 = selectedCountry; }); } // 调用时传入标识,区分存储到对应变量 controlFlag(select1, 'flag1', 'first'); controlFlag(select2, 'flag2', 'second'); function getRates(currency_name) { if(currency_name === "pln"){ return Promise.resolve(1); // 返回Promise,保证函数返回类型统一 } return fetch(`http://api.nbp.pl/api/exchangerates/rates/a/${currency_name}`) .then((response) => { if (!response.ok) throw new Error('汇率请求失败'); // 增加响应状态检查 return response.json(); }) .then(json_data => { const value_in_pln = json_data.rates[0].mid; return value_in_pln; }) .catch(error => { console.error(error); return null; // 出错时返回null,避免后续计算异常 }); } document.addEventListener('DOMContentLoaded', () => { if (conversionButton) { conversionButton.addEventListener('click', () => { // 取出存储的货币值 const curr1 = selectedCurrency1; const curr2 = selectedCurrency2; // 传入参数调用getRates Promise.all([getRates(curr1), getRates(curr2)]) .then(values => { const [rate1, rate2] = values; // 检查是否有请求失败的情况 if (!rate1 || !rate2) { outputRatio.innerHTML = '汇率获取失败,请重试'; return; } const amount = parseFloat(valueForInput.value) || 0; const conversionResult = (amount * (rate1 / rate2)).toFixed(4); outputRatio.innerHTML = `${amount} ${curr1} => ${conversionResult} ${curr2}`; }); }); } else { console.log("按钮元素未找到"); } });
关键改动说明
- 新增货币值存储:通过全局变量
selectedCurrency1和selectedCurrency2保存每次select选中的货币,在controlFlag的change事件中实时更新,初始化时也设置默认值。 - 修正
getRates()返回值:当货币为pln时,返回Promise.resolve(1),保证函数始终返回Promise类型,与fetch的返回值统一,避免Promise.all()执行异常。 Promise.all()传参:直接在getRates()中传入存储的货币值curr1和curr2,即可获取对应货币的汇率。- 增强错误处理:增加了fetch的响应状态检查,以及计算前的非空判断,避免页面显示异常内容。
内容的提问来源于stack exchange,提问作者PsimonL
相关产品推荐
相关产品推荐

