async function getChampionID(randomChampionID) {
let response = await fetch('http://ddragon.leagueoflegends.com/cdn/11.10.1/data/en_US/champion.json');
let body = await response.json();
var championData = Object.keys(body.data)
var randomChampionKey = Math.floor(Math.random() * (154 - 0 + 1) + 0)
return randomChampionID = championData[randomChampionKey]
}
async function getChampionName(randomChampionName) {
let result = await getChampionID();
let response = await fetch(`http://ddragon.leagueoflegends.com/cdn/11.10.1/data/en_US/champion/${result}.json`)
let body = await response.json();
return randomChampionName = body.data[result].name
}
var randomChampion = document.getElementById('random-champion')
var bgimg = document.getElementById('background-image')
var championSquare = document.getElementById('square')
randomChampion.addEventListener("click", async () =>
{
let championID = await getChampionID()
let championName = await getChampionName()
bgimg.style.backgroundImage = `url('http://ddragon.leagueoflegends.com/cdn/img/champion/splash/${championID}_0.jpg')`
championSquare.src=`http://ddragon.leagueoflegends.com/cdn/11.11.1/img/champion/${championID}.png`
console.log(championID)
console.log(championName)
})
getChampionName()
函数从 getChampionID
中获取一个随机值,因此每当我通过按钮事件侦听器调用它们时,getChampionID()
都会生成一个随机 ID(#1), getChampionName()
再次从 getChampionID()
获取另一个值,导致不同的 ID (#2),但我需要 getChampionName()
来获取 #1 ID
答案 0 :(得分:0)
首先,函数没有被传递参数,因此在定义时不需要括号内的任何内容。
其次,在事件侦听器中,我会简单地调用一个名为 getChampion
的函数,该函数获取一个随机 ID,然后获取详细信息,并返回冠军详细信息和 ID 以进一步用作对象。< /p>
我的代码看起来像这样。
async function getChampionID() {
let response = await fetch('http://ddragon.leagueoflegends.com/cdn/11.10.1/data/en_US/champion.json');
let body = await response.json();
var championData = Object.keys(body.data)
var randomChampionKey = Math.floor(Math.random() * (154 - 0 + 1) + 0)
return championData[randomChampionKey]
}
async function getChampion() {
let result = await getChampionID();
let response = await fetch(`http://ddragon.leagueoflegends.com/cdn/11.10.1/data/en_US/champion/${result}.json`)
let body = await response.json();
return { name: body.data[result].name, id: result }
}
var randomChampion = document.getElementById('random-champion')
var bgimg = document.getElementById('background-image')
var championSquare = document.getElementById('square')
randomChampion.addEventListener("click", async () =>
{
let champion = await getChampion()
bgimg.style.backgroundImage = `url('http://ddragon.leagueoflegends.com/cdn/img/champion/splash/${champion.id}_0.jpg')`
championSquare.src=`http://ddragon.leagueoflegends.com/cdn/11.11.1/img/champion/${champion.id}.png`
console.log(champion.id)
console.log(champion.name)
})