简体   繁体   中英

Can't add listeners to buttons created by another button

First of all, I'm a newbie at programming.

I have a button (Canciones) that creates multiple buttons in the empty div (to the right), but I can't add EventListeners to them, I cannot make it work. I think that maybe the Listeners are on, but they don't work 'cause they "can't read property of undefined" . I don't understand what's happening, but I wasted a lot of time trying to solve it by myself.

let canciones = [
    {
        nombre: "Heroes",
        portada: "img/album/davidBowieHeroes.jpg",
        audio: "music/davidBowieHeroes.mp3",
        autor: "David Bowie",
        album: "Heroes",
        genero: "Rock Pop"
    },
    {
        nombre: "Detroit Rock City",
        portada: "img/album/kissDestroyer.jpg",
        audio: "music/kissDetroitRockCity.mp3",
        autor: "Kiss",
        album: "Destroyer",
        genero: "Rock"
    },
    {
        nombre: "Bycicle Race",
        portada: "img/album/queenJazz.jpg",
        audio: "music/queenBycicleRace.mp3",
        autor: "Queen",
        album: "Jazz",
        genero: "Rock"
    },
    {
        nombre: "Livin' On A Prayer",
        portada: "img/album/bonJoviSlipperyWhenWet.jpg",
        audio: "music/bonJoviLivin'OnAPrayer.mp3",
        autor: "Bon Jovi",
        album: "Slippery When Wet",
        genero: "Rock"
    },
    {
        nombre: "I'm Just a Singer in a Rock and Roll Band",
        portada: "img/album/theMoodyBluesSeventhSojourn.jpg",
        audio: "music/theMoodyBluesI'mJustASingerInRockAndRollBand.mp3",
        autor: "The Moody Blues",
        album: "Seventh Sojourn",
        genero: "Rock"
    },
    {
        nombre: "London Calling",
        portada: "img/album/theClashLondonCalling",
        audio: "music/theClashLondonCalling.mp3",
        autor: "The Clash",
        album: "London Calling",
        genero: "Punk"
    },
    {
        nombre: "Master Of Puppets",
        portada: "img/album/metallicaMasterOfPuppets.jpg",
        audio: "music/metallicaMasterOfPuppets.mp3",
        autor: "Metallica",
        album: "Master Of Puppets",
        genero: "Heavy Metal"
    },
    {
        nombre: "Hangar 18",
        portada: "img/album/megadethRustInPeace.jpg",
        audio: "music/megadethHangar18.mp3",
        autor: "Megadeth",
        album: "Rust In Peace",
        genero: "Heavy Metal"
    },
    {
        nombre: "Some Might Say",
        portada: "img/album/oasisMorningGlory.jpg",
        audio: "music/oasisSomeMightSay.mp3",
        autor: "Oasis",
        album: "Morning Glory",
        genero: "Rock"
    },
    {
        nombre: "God Only Knows",
        portada: "img/album/theBeachBoysPetSounds.jpg",
        audio: "music/theBeachBoysGodOnlyKnows.mp3",
        autor: "The Beach Boys",
        album: "Pet Sounds",
        genero: "Rock"
    }
]

const nombreCancion = document.getElementById("nombreCancion");
const imgAlbum = document.getElementById("imgAlbum");
const cancion = document.getElementById("cancion");
const nombreAutor = document.getElementById("nombreAutor");
const albumCancion = document.getElementById("albumCancion");
const genero = document.getElementById("genero");
const cancionesA = document.getElementById("canciones");

var i = 0;

function boton1() {
    cancionesA.innerHTML = "";
    for (i = 0; i < canciones.length; i++) {
        let boton = document.createElement("button");   
        boton.innerText = canciones[i].nombre; 
        boton.setAttribute("class", "cancion");
        boton.addEventListener('click', function(){
            cambiarCancion(canciones);
        });
        cancionesA.appendChild(boton);
    }
}

function cambiarCancion() { 
        nombreCancion.innerText = canciones[i].nombre;
        imgAlbum.src = canciones[i].portada;
        cancion.src = canciones[i].audio;
        nombreAutor.innerText = canciones[i].autor;
        albumCancion.innerText = canciones[i].album;
        genero.innerText = canciones[i].genero;
}

the Listeners don't work.

Perhaps the simplest solution is to add one event listener to the parent element (cancionesA) instead and catch clicks from the child elements as they bubble up the DOM. This is known as event delegation . In your button loop you can assign an id to each button which you can then use to identify the button that was clicked.

 let canciones = [{"nombre":"Heroes","portada":"img/album/davidBowieHeroes.jpg","audio":"music/davidBowieHeroes.mp3","autor":"David Bowie","album":"Heroes","genero":"Rock Pop"},{"nombre":"Detroit Rock City","portada":"img/album/kissDestroyer.jpg","audio":"music/kissDetroitRockCity.mp3","autor":"Kiss","album":"Destroyer","genero":"Rock"},{"nombre":"Bycicle Race","portada":"img/album/queenJazz.jpg","audio":"music/queenBycicleRace.mp3","autor":"Queen","album":"Jazz","genero":"Rock"},{"nombre":"Livin' On A Prayer","portada":"img/album/bonJoviSlipperyWhenWet.jpg","audio":"music/bonJoviLivin'OnAPrayer.mp3","autor":"Bon Jovi","album":"Slippery When Wet","genero":"Rock"},{"nombre":"I'm Just a Singer in a Rock and Roll Band","portada":"img/album/theMoodyBluesSeventhSojourn.jpg","audio":"music/theMoodyBluesI'mJustASingerInRockAndRollBand.mp3","autor":"The Moody Blues","album":"Seventh Sojourn","genero":"Rock"},{"nombre":"London Calling","portada":"img/album/theClashLondonCalling","audio":"music/theClashLondonCalling.mp3","autor":"The Clash","album":"London Calling","genero":"Punk"},{"nombre":"Master Of Puppets","portada":"img/album/metallicaMasterOfPuppets.jpg","audio":"music/metallicaMasterOfPuppets.mp3","autor":"Metallica","album":"Master Of Puppets","genero":"Heavy Metal"},{"nombre":"Hangar 18","portada":"img/album/megadethRustInPeace.jpg","audio":"music/megadethHangar18.mp3","autor":"Megadeth","album":"Rust In Peace","genero":"Heavy Metal"},{"nombre":"Some Might Say","portada":"img/album/oasisMorningGlory.jpg","audio":"music/oasisSomeMightSay.mp3","autor":"Oasis","album":"Morning Glory","genero":"Rock"},{"nombre":"God Only Knows","portada":"img/album/theBeachBoysPetSounds.jpg","audio":"music/theBeachBoysGodOnlyKnows.mp3","autor":"The Beach Boys","album":"Pet Sounds","genero":"Rock"}]; const nombreCancion = document.getElementById("nombreCancion"); const cancionesA = document.getElementById("canciones"); function boton1() { // Create a document fragment to save on DOM hits const frag = document.createDocumentFragment(); // For each button canciones.forEach((current, index) => { let boton = document.createElement("button"); boton.innerText = current.nombre; // Add the index as a data attribute boton.dataset.id = index; boton.setAttribute("class", "cancion"); // Append the button the fragment frag.appendChild(boton); }); // Finally append the fragment to the parent element cancionesA.appendChild(frag) } // Add one event listener to the parent element cancionesA.addEventListener('click', cambiarCancion, false); function cambiarCancion(e) { // Destructure the id from the target element (the // button that was clicked) const { target: { dataset: { id } } } = e; nombreCancion.innerText = canciones[id].nombre; } boton1();
 <div id="canciones"></div> <div id="nombreCancion"></div>

Further reading

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM