實作需求分析

- 抓取api提供的匯率資料:使用jQuery,ajax
- 選擇不同幣別,進行匯率換算
- swap按鈕,使幣別交換
完成後的成品
jQuery.ajax 使用
- 參考資料:jQuery.ajax()
1 | $.ajax({ |

- 應用於exchangeRate:
1
2
3
4
5
6
7
8
9
10
11
12
13$.ajax({
url: `https://v6.exchangerate-api.com/v6/06f04b805743079a1966771a/latest/${currency_one}`, //注意符號
method: 'get',//get,post,put
dataType: 'json',
success: function (data) {
//console.log(data);
const rate = data.conversion_rates[currency_two];
//console.log(rate);
$('#rate').text(`1 ${currency_one} = ${rate} ${currency_two}`);
$('#amount-two').val((amountOne * rate).toFixed(2));
}
}) 詳細說明可以參照內文:計算匯率calculate函式
其他參考資料:
[ Alex 宅開發 ] 👨💻從 jQuery 入門到認識 JavaScript #5 Ajax 與非同步功能操作與原始碼探索
1 | - `url`:來源,api的位置在哪裏 |
1 |
|
計算匯率calculate 函式
- 此函式為抓取匯率api的資料並帶入計算匯率
1 | function calculate() { |
函式說明:
1.先將要抓取的值,宣告變數;分別有選擇的國家幣別、兌換的數量
2.串接資料
(1). 抓取資料的位置url: https://v6.exchangerate-api.com/v6/06f04b805743079a1966771a/latest/${currency_one}
注意網址:"https://v6.exchangerate-api.com/v6/06f04b805743079a1966771a/latest/USD"
注意網址後面有修改,要抓取會變動的變數: ${currency_one}
(2) 檢查是否有抓到要的資料:
- 宣告:
const rate = data.conversion_rates[currency_two]; - console.log(rate);

- 確定抓取的值是否正確:
console.log($('#amount-two').val());

- 將計算匯率帶入
$('#amount-two').val((amountOne * rate).toFixed(2));

其他輸入值的抓取與連動
1 | $("#currency-one").change(function () { |
1 |
|
發現使用
.append(),會出現累積div文字的問題(1) 清除函式
.append(),累積div文字呈現的問題$("#rate").html("");(2) 將原本使用
.append()的地方,修改為.text(),$('#rate').text(`1 ${currency_one} = ${rate} ${currency_two}`);


swap按鈕 (使幣別交換)
- 宣告一個變數,紀錄交換前的幣別
let temp = $("#currency-one").val(); - 確認是否宣告正確:
console.log(temp);


1 | //swap按鈕 |
console.log($("#currency-one").val());console.log($("#currency-two").val());
