我已经做了一个简单的货币转换器Chrome扩展,我试图让它触发我的convert
功能时,点击进入我的号码输入与amount
的id。
HTML
<!DOCTYPE html>
<html>
<head>
<title>convertFrom Currency Converter</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
</head>
<body>
<form>
<div class="convertFrom">
<select id="convertFrom">
<option value="ETH">ETH</option>
<option value="BTC">BTC</option>
<option value="SOL">SOL</option>
</select>
</div>
<div class="convertTo">
→
<select id="convertTo">
<option value="BTC">BTC</option>
<option value="ETH">ETH</option>
<option value="SOL">SOL</option>
<option value="USD">USD</option>
</select>
</div>
<div class="amountToConvert">
<input type="number" placeholder="0.05" id="amount" autofocus required>
</div>
<div class="convertButton">
<button type="button" id="convertButton" name="convertButton">Convert</button>
<script src="popup2.js"></script>
</div>
</form>
<div id="result"></div>
<script src="popup2.js"></script>
</body>
</html>
Javascript
document.getElementById("convertButton").addEventListener("click", convert);
document.getElementById("amount").addEventListener("keydown", function(event) {
if (event.key === 'Enter') {
convert();
}
});
function convert() {
let convertFrom = document.getElementById("convertFrom").value;
let convertTo = document.getElementById("convertTo").value;
let amount = document.getElementById("amount").value;
let url = `https://min-api.cryptocompare.com/data/price?fsym=${convertFrom}&tsyms=${convertTo}`;
fetch(url)
.then(response => response.json())
.then(data => {
let rate = data[convertTo];
let result = amount * rate;
document.getElementById("result").innerHTML = `${amount} ${convertFrom} = ${result.toFixed(4)} ${convertTo}`;
})
.catch(error => console.log(error));
}
Manifest.json
{
"name": "Crypto Currency Converter",
"description": "A simple crypto currency converter.",
"version": "0.1",
"manifest_version": 3,
"action": {
"default_popup": "popup/ccc.html"
}
}
如果我点击它,现在提交作品的按钮,但是当我点击"Enter"时,数字输入重置(清除),失去焦点,并且它似乎没有触发convert
功能。
我想让它,当我点击按钮,或按回车键转换功能将被触发。
扩展内没有服务器,所以您的<form>
只是重置页面。去掉这个标签,你不需要它了。