Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

232
Views
la función funciona al cargar la página pero no al hacer clic en el botón

Estoy tratando de hacer que mi aplicación web se ejecute cuando se hace clic, pero solo funciona cuando la página se carga inicialmente. Si sigo presionando f5, seleccionará un elemento al azar y funcionará correctamente. Pero me gustaría que lo hiciera cuando se presione el botón 'siguiente'.

Estoy intentando cambiar la identificación de 'ubicaciónTítulo' a un elemento aleatorio de myArray.

Cuando abro las herramientas de desarrollo y hago clic en el botón 'SIGUIENTE', parpadea el valor 'ubicación del título' del div.

 let myArray = [ 'Boardwalk', 'Highland Park', 'Waterfront', 'Beach', 'North End', 'Canal', 'Wiley Island', 'Conservation Park', 'Dufferin Falls', 'Old Town', ] const random = Math.floor(Math.random() * myArray.length); console.log(myArray[random]); let my_btn = document.getElementById("my_btn"); function nextElement() { document.getElementById("locationTitle").innerHTML = (myArray[random]); } window.addEventListener("load", nextElement); my_btn.addEventListener("click", nextElement); html: <button id = "my_btn" onclick = "nextElement()" ;>NEXT</button>
about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

Parece que la función se llama cada vez que hace clic en el botón, pero elige su valor aleatorio una vez al comienzo del script y usa el mismo valor cada vez.

Si mueve la selección de valor aleatorio a la función, de modo que la función se lea de la siguiente manera, debería ver que cambia a un valor diferente cada vez:

 ... function nextElement() { const random = Math.floor(Math.random() * myArray.length); document.getElementById("locationTitle").innerHTML = (myArray[random]); } ...
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!