javascript - Vanilla JavaScript 根据 <option> 值更改 api 端点

标签 javascript html css

我正在使用以下工具创建一个货币转换器应用程序:' https://exchangeratesapi.io/ ' API,我正在尝试根据使用来自 API 的数据动态创建并添加到 currencyArr[] 并循环创建每个选项的端点 'base=' 来更改端点。我想控制更改 og URL 的标签具有 ID“top-select”

例如,如果选择 GBP,则 url 应类似于“https://api.exchangeratesapi.io/latest?base=GBP”。

我看到过基于 React、JQuery 或 AJAX 的类似问题,但我使用的是原生 JavaScript,但我还不知道如何使用这些库。

let currencyArr = [];
let ratesArr = [];
window.addEventListener("load", () => {
	let api = "https://api.exchangeratesapi.io/latest?base=";
	fetch(api)
		.then(response => {
			return response.json();
		})
		.then(data => {
			for (currency in data.rates) {
				currencyArr.push(currency);
				ratesArr.push(data.rates[currency]);

				// create 'option' element here
				const optionTop = document.createElement("option");
				const optionBottom = document.createElement("option");
				optionTop.textContent = currency;
				optionBottom.textContent = currency;
				document.querySelector("#top-select").appendChild(optionTop);
				document.querySelector("#bottom-select").appendChild(optionBottom);
			}

			document.querySelector("#input").addEventListener("keyup", convert);
			document
				.querySelector("#bottom-select")
				.addEventListener("change", convert);
			function convert() {
				const input = document.querySelector("#input");
				let bottomSelectValue = document.querySelector("#bottom-select").value;

				for (let i = 0; i < currencyArr.length; i++) {
					if (bottomSelectValue === currencyArr[i]) {
						document.querySelector("#converted").value = parseFloat(
							ratesArr[i] * input.value
						).toFixed(2);
					}
					if (isNaN(document.querySelector("#converted").value)) {
						document.querySelector("#converted").value =
							"Please Enter A Number";
					}
				}
			}
		});
});
html {
	font-family: "Lato", sans-serif;
	font-weight: thin;
	background-image: linear-gradient(to right top, #90d0ff, #008ef7);
	color: white;
	height: 100vh;
	overflow: hidden;
}
h1 {
	text-align: center;
	font-size: 5em;
}
.container {
	width: 100%;
	height: 80%;
	display: flex;
	align-items: center;
	flex-direction: column;
	text-align: center;

	justify-content: center;
	align-items: center;
}

.container input {
	background: transparent;
	border: none;
	border-bottom: 0.5vh solid white;
	font-size: 7em;
	max-width: 100%;
	outline: none;
	font-family: "Lato", sans-serif;
	font-weight: thin;
	color: white;
	text-align: center;
	overflow: visible;
}
::placeholder {
	/* Chrome, Firefox, Opera, Safari 10.1+ */
	color: white;
	opacity: 1;
	/* Firefox */
}

:-ms-input-placeholder {
	/* Internet Explorer 10-11 */
	color: white;
}

::-ms-input-placeholder {
	/* Microsoft Edge */
	color: white;
}

.container select {
	background: transparent;
	color: white;
	padding: 20px;
	width: 80px;
	height: 60px;
	border: none;
	font-size: 20px;
	box-shadow: 0 5px 25px rgba(0, 0, 0, 0.5);
	-webkit-appearance: button;
	outline: none;
	margin-top: 5%;
}
.converted {
	pointer-events: none;
	margin-top: 5%;
}
 
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<title>Currency Converter</title>
		<meta name="viewport" content="width=device-width, initial-scale=1" />
		<link rel="stylesheet" href="main.css" />
		<link
			href="https://fonts.googleapis.com/css?family=Lato:300&display=swap"
			rel="stylesheet"
		/>
	</head>

	<body>

	
			<h1>Currency Converter</h1>
			
			<div class="container" id="ctn1">
				<input type="text"  id="input" autocomplete="off" placeholder="Enter your number" onfocus="this.placeholder = ''" onblur="this.placeholder ='Enter your number'"/>

				<select id="top-select"> </select>
		

			<div class="container" id="ctn2">
				<input type="text" class="converted" id="converted" autocomplete="off" placeholder="0.00" />
				<select id="bottom-select"> </select>
			</div>
		
		<script src="main.js"></script>
	</body>
</html>

Codepen 链接只是为了防止 API 在 Stack Overflow 片段中不起作用:https://codepen.io/oliknight/pen/rXaBBZ

最佳答案

你只需要设置一个包含你想要获取的硬币的变量,以及一个用于选择器的监听函数 onchange ,所以每次你改变选择器时,获取函数都会再次运行,但是您想要的基值。

这是工作片段(我把它变小以便适合页面):

const baseUrl = 'https://api.exchangeratesapi.io/latest?base='
const topSelector = document.getElementById('top-select')
const bottomSelector = document.getElementById('bottom-select')
const converted = document.querySelector('#converted')
const input = document.querySelector('#input')

window.addEventListener('load', () => {
  fetchCurrencyList()
  topSelector.addEventListener('change', convert)
  bottomSelector.addEventListener('change', convert)
  input.addEventListener('keyup', convert)
})

function fetchCurrencyList() {
  return fetchJson(baseUrl + topSelector.value).then((data) => {
    data.rates[data.base] = 1
    for (const currency in data.rates) {
      const optionItem = document.createElement('option')
      const optionItem2 = document.createElement('option')
      optionItem.text = currency
      optionItem.value = data.rates[currency]
      optionItem2.text = currency
      optionItem2.value = data.rates[currency]
      topSelector.appendChild(optionItem)
      bottomSelector.appendChild(optionItem2)
    }
    convert()
  })
}

function convert() {
  const bottomSelectValue = bottomSelector.value
  const topSelectValue = topSelector.value

  converted.value = parseFloat(
    topSelectValue * input.value / bottomSelectValue
  ).toFixed(2)

  if (!converted.value || isNaN(converted.value)) {
    converted.value = 'Please Enter A Number'
  }
}

function fetchJson(url) {
  return fetch(url)
    .then((response) => {
      return response.json()
    })
}
html {
	font-family: "Lato", sans-serif;
	font-weight: thin;
	background-image: linear-gradient(to right top, #90d0ff, #008ef7);
	color: white;
	height: 100vh;
	overflow: hidden;
}
.container {
	width: 100%;
	height: 80%;
	display: flex;
	align-items: center;
	flex-direction: column;
	text-align: center;

	justify-content: center;
	align-items: center;
}

.container input {
	background: transparent;
	border: none;
	border-bottom: 0.1vh solid white;
	font-size: 2em;
	max-width: 100%;
	outline: none;
	font-family: "Lato", sans-serif;
	font-weight: thin;
	color: white;
	text-align: center;
	overflow: visible;
}
::placeholder {
	/* Chrome, Firefox, Opera, Safari 10.1+ */
	color: white;
	opacity: 1;
	/* Firefox */
}

:-ms-input-placeholder {
	/* Internet Explorer 10-11 */
	color: white;
}

::-ms-input-placeholder {
	/* Microsoft Edge */
	color: white;
}

.container select {
	background: transparent;
	color: white;
  padding: 0px 14px;
	width: 80px;
	height: 30px;
	border: none;
	font-size: 14px;
	box-shadow: 0 5px 25px rgba(0, 0, 0, 0.5);
	-webkit-appearance: button;
	outline: none;
	margin-top: 1%;
}
.converted {
	pointer-events: none;
	margin-top: 5%;
}
 
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<title>Currency Converter</title>
		<meta name="viewport" content="width=device-width, initial-scale=1" />
		<link rel="stylesheet" href="main.css" />
		<link
			href="https://fonts.googleapis.com/css?family=Lato:300&display=swap"
			rel="stylesheet"
		/>
	</head>

	<body>
	<div class="container" id="ctn1">
				<input type="text" id="input" autocomplete="off" placeholder="Enter your number" onfocus="this.placeholder = ''" onblur="this.placeholder ='Enter your number'"/>

				<select id="top-select"> </select>
			<div class="container" id="ctn2">
				<input type="text" class="converted" id="converted" autocomplete="off" placeholder="0.00" />
				<select id="bottom-select"> </select>
			</div>
		
		<script src="main.js"></script>
	</body>
</html>

编辑:原始代码中还有其他错误需要修复,因此我编辑了代码片段以使其按预期工作。对比率使用一个对象而不是 2 个数组是理想的,依赖索引号的风险太大。

关于javascript - Vanilla JavaScript 根据 <option> 值更改 api 端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57102841/

相关文章:

javascript - jQuery - 动态创建类以匹配现有类

html - 按钮悬停不适用于透明

php - 限制php代码中数据库的数据

javascript - 如何在 onclick 事件上发送标签的值

html - 如果为空则隐藏表行

html - 否决框阴影

javascript - 我可以一键设置状态并调用函数吗?

javascript - Dropzone 上传到 Flask 应用后不会重定向

javascript - 填充 3 个动态下拉菜单

javascript - 使用combineReducers后组件停止更新