gpt4 book ai didi

javascript - 为什么我的点击事件在生成 HTML 时只工作一次,但在 console.logging 时工作正常?

转载 作者:行者123 更新时间:2023-12-01 00:13:06 26 4
gpt4 key购买 nike

它按照我想要的方式在控制台中以及生成 HTML 时运行,但它仅适用于 HTML 一次,而它始终适用于控制台。我需要在这里使用循环并以这种方式返回 HTML 吗?我尝试了 map ,但它不是一个数组。编辑:忘记了 HTML,只是添加了它。

<!DOCTYPE html>
<html>
<head>
<title>Pokedex</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<h1 id="main-header">Pokedex</h1>
<div id="main-container">

</div>
<script src="index.js" type="text/javascript"></script>
</body>
</html>

Javascript

const container = document.getElementById('main-container');

function getPokemon(callback) {
const xhr = new XMLHttpRequest();
const url = 'https://pokeapi.co/api/v2/pokemon/';

xhr.onload = function() {
if(xhr.status === 200) {
const pokemon = JSON.parse(xhr.responseText);
container.innerHTML+=
pokemon.results.map((poke, index)=>{
return `
<div class='cardFront'>
<img src='https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${(index + 1).toString()}.png'></img>
<h4>${poke.name}</h4>
</div>
`
}).join('');

callback();
}
}
xhr.open('GET', url, true);
xhr.send();
}

function cardBack() {
const endPoint = this.lastChild.previousSibling.innerText;
const xhr = new XMLHttpRequest();

xhr.onload = function() {
if(xhr.status === 200) {
const details = JSON.parse(xhr.responseText);
container.innerHTML+= `
<div class='backSide'>
<h4>${details.name}</h4>
<h4>${details.types[0].type.name}</h4>
</div>
`
}
}
xhr.open('GET', 'https://pokeapi.co/api/v2/pokemon/' + endPoint, true);
xhr.send();
}

getPokemon(()=>{
const cardFront = document.querySelectorAll('.cardFront');
cardFront.forEach((card)=> {
card.addEventListener('click', cardBack);
})
});

最佳答案

在点击监听器的回调函数内,您将新的 html 代码添加到主容器 <div>元素使用其 .innerHTML 属性。这将删除所有现有的事件监听器 - 因此单击只会触发一次。

尽管我建议创建一个新的 <div>使用

var newDiv = document.createElement("DIV");

并将其附加到主容器中

document.getElementById('main-container').appendChild(newDiv);

您的情况更简单的解决方案是替换

container.innerHTML+= `
<div class='backSide'>
<h4>${details.name}</h4>
<h4>${details.types[0].type.name}</h4>
</div>
`

container.insertAdjacentHTML("afterend", `
<div class='backSide'>
<h4>${details.name}</h4>
<h4>${details.types[0].type.name}</h4>
</div>
`);

关于javascript - 为什么我的点击事件在生成 HTML 时只工作一次,但在 console.logging 时工作正常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59938078/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com