首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

JavaScript 下拉聯動:選擇幣種自動計算並動態生成兌換表格

     編輯:程式設計疑難解答

需求

選擇基準幣種、輸入金額,自動查詢匯率表,動態生成「目標幣種、兌換金額、匯率」表格。

完整可運行解決方案(原生 JS,無依賴)

<form name="messageForm">
  <div class="refitem">
    基準幣種:<select onchange="outputRst()" id="sMoney">
      <option>請選擇..</option>
      <option>美元</option>
      <option>人民幣</option>
      <option>英鎊</option>
      <option>日元</option>
    </select>
    金額<input type="text" id="amount" onchange="outputRst()" />
  </div>
  <br/><br/>
  <table id="tbRst" border="1">
    <tr><td>幣種</td><td>兌換金額</td><td>匯率</td></tr>
  </table>
</form>

<script>
// 匯率基準:以美元為中介
const rate = {
  美元: { 人民幣: 6.5781, 英鎊: 0.6943, 日元: 119.53, 美元: 1 }
};
const allCurrencies = '美元,人民幣,英鎊,日元';

const tbRst = document.getElementById('tbRst');
const sel = document.getElementById('sMoney');

function outputRst() {
  // 清空舊行
  while (tbRst.rows.length > 1) tbRst.deleteRow(-1);
  
  if (sel.selectedIndex === 0) return; // 未選擇
  
  const base = sel.options[sel.selectedIndex].text; // 基準幣種
  const amount = parseFloat(document.getElementById('amount').value) || 0;
  
  // 目標幣種 = 所有幣種 - 基準幣種
  const targets = allCurrencies.split(',').filter(c => c !== base);
  
  targets.forEach(t => {
    let r;
    if (base === '美元') r = rate.美元[t]; // 直接查表
    else r = 1 / rate.美元[base] * rate.美元[t]; // 交叉匯率計算
    
    const row = tbRst.insertRow();
    row.insertCell().textContent = t;
    row.insertCell().textContent = (r * amount).toFixed(2);
    row.insertCell().textContent = r.toFixed(4);
  });
}
</script>

核心邏輯解析

步驟關鍵代碼
清空舊數據`while (tbRst.rows.length > 1) tbRst.deleteRow(-1);`
獲取基準幣種與金額`sel.options[sel.selectedIndex].text`、`parseFloat(...)`
計算目標幣種列表`allCurrencies.split(',').filter(c => c !== base)`
匯率換算直接查表 或 `1/rate[base]*rate[target]` (交叉匯率)
動態生成行`insertRow()` + `insertCell()` + `textContent`

擴展建議

  • 匯率從後端 API 獲取:`fetch('/api/rates').then(r=>r.json()).then(data=>{ rates=data; outputRst(); })`。
  • 支援反向換算:輸入目標金額反推基準金額。
  • 增加歷史匯率圖表(Chart.js/ECharts)。
  • 金額輸入防抖:`oninput="debounce(outputRst,300)"` 避免頻繁計算。

**純前端即可實現完整匯率換算工具,核心是「以單一基準幣種為中介」計算交叉匯率。**

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved