如何将连接按钮值添加到api中



所以我正在制作一个假日查找器"应用程序",我想有一些按钮,当有人点击他们国家的名称时,它会将国家的值输入到api字符串中。

我所做的是遍历所有按钮,并将目标值保存到一个变量中,然后将其连接到api中。问题是,当我在控制台中查看获取的api时,国家代码应该在哪里,它说"未定义"。

我有点困惑为什么,所以如果你找到了解决方案,请解释一下。

let countrySelect = document.getElementById('country-select');
let holidayName = document.getElementById('holiday-name');
let holidayDesc = document.getElementById('holiday-desc');
let holidayDate = document.getElementById('holiday-date');
let holidayType = document.getElementById('holiday-type');
let info = document.querySelector('.cell');
let buttonValue;
// get button values
const button = document.querySelectorAll("button").forEach(
button => button.addEventListener('click', function(e) {
buttonValue = e.target.value;
console.log(buttonValue)
})
);

// api url
const api = `https://calendarific.com/api/v2/holidays?&api_key=<api key>&country=${buttonValue}&year=2020`;

// When the button is clicked fetch results
countrySelect.addEventListener('click', function() {
fetch(api)
.then(res => res.json())
.then(data => {
var apiResponse = data.response;

console.log(apiResponse);
}, networkError => {
alert(networkError)
})
})

您需要在countrySelect事件侦听器中定义/重新定义api变量。

目前,它是在单击任何按钮之前定义的,因此buttonValue是未定义的。因此,即使您的buttonValue随着按钮的点击而发生变化,api变量也会保持原样,即country=undefined

let countrySelect = document.getElementById('country-select');
let buttonValue;

const button = document.querySelectorAll("button").forEach(
button => button.addEventListener('click', function(e) {
buttonValue = e.target.value;
console.log(buttonValue);
})
);
// When the button is clicked fetch results
countrySelect.addEventListener('click', function() {
	const api = `https://calendarific.com/api/v2/holidays?&api_key=<api key>&country=${buttonValue}&year=2020`;
	
	console.log(api);
});
#country-select {
border: 1px solid green;
color: green;
display: inline-block;
cursor: pointer;
}
<button value='uk'>
UK
</button>
<button value ='us'>
US
</button>
<div id='country-select'>
Select Country
</div>

最新更新