¿Cómo hacer que js muestre una palabra aleatoria de una lista con un clic de un botón e imprimirla en un encabezado 3? Necesito una respuesta rápida. Por favor, agradecería una respuesta rápida.
// Comienzo del código Js
let display = document.getElementById("motivato"); console.log(display) var motivation = [{ quote: "Planting popcorn does not produce more popcorn", person: "Farmer Ted" }, { quote: "White whale, bad whale", person: "Confucious (Moby Dick)" }, { quote: "Use the strobe function to disorientate your attacker", person: "Flashlight" }, { quote: "Apply liberally to your erogenous zones", person: "Spice Bomb" }, { quote: "Help me, I'm bleaching", person: "The Great Barrier Reef" }]; function motivateMe() { var listLength = Object.keys(motivation).length; var randVal = Math.floor(Math.random() * listLength); document.write(motivation[randVal]); display.innerHTML = motivation; }Edite mi código y responda a continuación.
Gracias
Voy a suponer que querías decir que querías generar una cita aleatoria y no solo una palabra.
Aquí está la respuesta:
const motivation = [{ quote: "Planting popcorn does not produce more popcorn", person: "Farmer Ted" }, { quote: "White whale, bad whale", person: "Confucious (Moby Dick)" }, { quote: "Use the strobe function to disorientate your attacker", person: "Flashlight" }, { quote: "Apply liberally to your erogenous zones", person: "Spice Bomb" }, { quote: "Help me, I'm bleaching", person: "The Great Barrier Reef" }]; const randomNumber = Math.floor(Math.random() * motivation.length); console.log(motivation[randomNumber]); const generate_quote = () => { const quote = motivation[randomNumber].quote; document.getElementById("random_quote").innerHTML = quote; } <p id="random_quote">The random quote will appear here.</p> <button onclick="generate_quote()">Generate random quote</button> const display = document.getElementById("motivato"); const motivation = [{ quote: "Planting popcorn does not produce more popcorn", person: "Farmer Ted" }, { quote: "White whale, bad whale", person: "Confucious (Moby Dick)" }, { quote: "Use the strobe function to disorientate your attacker", person: "Flashlight" }, { quote: "Apply liberally to your erogenous zones", person: "Spice Bomb" }, { quote: "Help me, I'm bleaching", person: "The Great Barrier Reef" }]; function motivateMe() { const listLength = motivation.length; const randVal = motivation[Math.floor(Math.random() * listLength)]; display.innerHTML = `<q>${randVal.quote}</q><br><br><small>${randVal.person}</small>`; } <button onclick="motivateMe()">Motivate me!</button> <h3 id="motivato"></h3>Ahora debe editar lo anterior para asegurarse de que al presionar un botón no se devuelva la misma cotización que la anterior, ya que cuando lo hace, parece que el botón no funciona.