No puedo acceder a este botón cuando intento acceder a otro archivo. ¿Funciona cuando lo hago dentro del primer archivo pero no puedo hacerlo en el archivo 2? Por cierto, Css funciona bien, si creo un archivo CSS y agrego algo de estilo a los elementos, funciona, pero no el javascript
file1.js else { product_carousel_wrapper.innerHTML = recent.map(productData => ` <h1>Hello</h1> <button class="click">CTest</button> <h1>Bye</h1> ` ).join(''); } file2.js document.querySelector('.click').addEventListener('click', () => { alert('Heyy'); });Adjunte un oyente al elemento contenedor y use la delegación de eventos para capturar eventos de elementos secundarios que se agregaron dinámicamente al DOM en lugar de adjuntar un oyente a cada botón.
// FILE1 // Cache the wrapper const wrapper = document.querySelector('.wrapper'); // Add the HTML wrapper.innerHTML = ` <button>CTest1</button> <button>CTest2</button> <button>CTest3</button> `; // FILE2 // Add a listener to the wrapper wrapper.addEventListener('click', handleClick, false); // Get the textContent (in this example) // of the button that was clicked function handleClick(e) { if (e.target.matches('button')) { console.log(e.target.textContent); } } <div class="wrapper"></div>