有一个带有随机笑话的按钮,根据类别显示一个笑话。类别列表是通过API请求https://api.chucknorris.io/jokes/categories
笑话输出是从https://api.chucknorris.io/jokes/random?category={category}
问题:根据以下代码单击类别时,如何获得特定名称{category}
(单击类别时,不应更新页面)?
function foo() {
let xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.chucknorris.io/jokes/categories', false);
xhr.send();
if (xhr.status !== 200) {
console.log(xhr.status + ` ` + xhr.statusText);
}
let dataObject = JSON.parse(xhr.responseText);
console.log(dataObject);
let menu = document.getElementById('menu');
dataObject.forEach(item => {
let div = document.createElement("div");
div.innerHTML = "<a href='" + item + "'>" + item + "</a>";
div.classList.add("div-added");
div.id = 'items';
menu.append(div);
});
let currentCategory;
let items = document.querySelectorAll("#items");
for (let i = 0; i < items.length; i++) {
items[i].addEventListener('click', function(e) {
e.preventDefault();
console.log(items[i]);
return false;
});
}
}
答案 0 :(得分:0)
function foo(){
let dataObject = getRemoteData('https://api.chucknorris.io/jokes/categories');
console.log(dataObject);
let menu = document.getElementById('menu');
dataObject.forEach(item => {
let div = document.createElement("div");
div.innerHTML = "<a href='javascript:void(0)' onclick=getJoke('" + item + "')>" + item + "</a>";
div.classList.add("div-added");
div.id = 'items';
menu.append(div);
});
}
function getJoke(token){
let jokeData = getRemoteData("https://api.chucknorris.io/jokes/random?category=" + token);
// Write code to use that joke data
console.log(jokeData);
}
function getRemoteData(url){
let xhr = new XMLHttpRequest();
xhr.open('GET', url, false);
xhr.send();
if (xhr.status !== 200) {
console.log(xhr.status + ` ` + xhr.statusText);
}
return JSON.parse(xhr.responseText);
}