我有三个按钮,所以当我单击按钮1时,该按钮函数调用并将字符串值存储到Endpoint,窗口应该重新加载更新的数据。。所以更新后的url应该是https://api_url_here/national
但问题是windows没有用更新的值重新编码
var btn1 = document.querySelector(".btn1");
var endpoint = [];
console.log(endpoint);
fetch(`https://api_url_here/${endpoint}`)
.then((response) => {
if (response.ok) {
return response.json();
} else {
throw new Error("Something went wrong");
}
})
.then((newsData) => {
console.log(newsData);
})
btn1.addEventListener("click", function () {
endpoint = "national";
console.log(endpoint);
});
<div class="menu">
<button class="btn1">national</button>
<button class="btn2">buisness</button>
<button class="btn3">politics</button>
</div>
单击按钮后,您应该调用API。目前,它在发生之前被称为。
我建议将fetch()
调用封装在一个函数中,使代码更加通用。此外,您可以在所有按钮上附加一个事件,并调用如下新功能:
var btn1 = document.querySelectorAll(".btn1");
btn1.forEach(function (btn) {
btn.addEventListener("click", function (e) {
callAPI(e.target.value);
});
});
function callAPI(endpoint) {
fetch(`https://api_url_here/${endpoint}`)
.then((response) => {
if (response.ok) {
return response.json();
} else {
throw new Error("Something went wrong");
}
})
.then((newsData) => {
console.log(newsData);
})
}
<div class="menu">
<button class="btn1" value="national">national</button>
<button class="btn1" value="business">buisness</button>
<button class="btn1" value="politics">politics</button>
</div>
需要使用querySelectorAll来获取所有按钮并将事件绑定到每个按钮:
var buttons = document.querySelectorAll(".menu-button");
function fetchData(endpoint) {
fetch(`https://api_url_here/${endpoint}`).then((response) => {
if (response.ok) {
return response.json();
} else {
throw new Error("Something went wrong");
}
})
.then((newsData) => {
console.log(newsData);
});
}
buttons.forEach(b => b.addEventListener("click", function (event) {
fetchData(event.target.getAttribute("data-value"));
}));
HTML:
<div class="menu">
<button class="menu-button" data-value="national">national</button>
<button class="menu-button" data-value="business">business</button>
<button class="menu-button" data-value="politics">politics</button>
</div>