Soy nuevo en JavaScript y estaba haciendo un generador de cotizaciones aleatorias, pero parece que no puedo hacer que mi código js se vincule al botón. ¿Tiene algo que ver con mis selectores?
let quotes = ['The greatest glory in living lies not in never falling, but in rising every time we fall.', 'The way to get started is to quit talking and begin doing.', 'If life were predictable it would cease to be life, and be without flavor.', 'Life is what happens when youre busy making other plans.', 'Spread love everywhere you go. Let no one ever come to you without leaving happier.']; let author = ['Nelson Mandela', 'Walt Disney', 'Eleanor Roosevelt', 'John Lennon', 'Mother Teresa']; const quoteId = document.querySelector('.quote'); const authorId = document.querySelector('.source'); const btn = document.getElementById('loadQuote'); btn.addEventListener('click', function() { quote.textContent = quotes[randomNum()]; source.textContent = author[randomNum()]; }); function randomNum() { Math.floor(Math.random() * quotes.length) }; <div id="quote-box"> <p class="quote">You can do anything but not everything</p> <p class="source">David Allen<span class="citation">Making It All Work</span><span class="year">2009</span></p> </div> <button id="loadQuote">Show another quote</button> </div>Hay diferentes errores:
En la función nombrada, debe escribir explícitamente "devolver" lo que desea que le devuelvan las funciones,
Suponiendo que "cita" y "autor" estén emparejados por su posición, debe usar un "randNum" común en la función pasada en el detector de eventos,
Otro tipo de error solucionado.
let quotes = [ "The greatest glory in living lies not in never falling, but in rising every time we fall.", "The way to get started is to quit talking and begin doing.", "If life were predictable it would cease to be life, and be without flavor.", "Life is what happens when youre busy making other plans.", "Spread love everywhere you go. Let no one ever come to you without leaving happier.", ]; let author = [ "Nelson Mandela", "Walt Disney", "Eleanor Roosevelt", "John Lennon", "Mother Teresa", ]; const quoteId = document.querySelector(".quote"); const authorId = document.querySelector(".source"); const btn = document.getElementById("loadQuote"); btn.addEventListener("click", function () { let randNum = randomNum(); quoteId.textContent = quotes[randNum]; authorId.textContent = author[randNum]; }); function randomNum() { return Math.floor(Math.random() * quotes.length); }He tenido este problema muchas veces en el pasado. Puedes hacer una de las dos cosas:
Puede cambiar btn.addEventListener('click', ...) a btn.onclick = function() { ... }
O bien, puede cambiar btn.addEventListener('click', ...) a btn.addEventListener('onclick')
Esto sucede porque se ejecuta la función 'clic' ya que es una consulta del elemento botón. Imagínelo como si estuviera dentro del elemento del botón donde haría <button onclick="myFunction()"></button> .