为什么我的click事件在生成HTML时只工作一次,而在console.logging时却能正常工作?

问题描述 投票:0回答:1

它的功能与我在控制台中的预期功能以及生成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);
})
});
javascript html ajax dom events
1个回答
0
投票

在点击侦听器的回调函数中,您正在使用其[[.innerHTML属性将新的html代码添加到您的主容器<div>元素中。这将删除所有现有的事件侦听器!

尽管我建议使用]创建一个新的[C0

<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> `

© www.soinside.com 2019 - 2024. All rights reserved.