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

102
Views
¿Cómo hago que las variables cambien fuera de las funciones en javascript?

Soy un principiante con Javascript/programación y estoy tratando de hacer que el id "demo2" cambie con la variable 5, 10 o 15 elegida en las funciones (disparador por los botones), pero sigue mostrando "0". ¿Que tengo que hacer?

 <!DOCTYPE html> <html> <body> <button onclick="alternative1()">5</button> <button onclick="alternative2()">10</button> <button onclick="alternative3()">15</button> <p id="demo"></p> <p id="demo2"></p> <script> var x = 0; var y = 0; function alternative1() {y = x + 5; document.getElementById("demo").innerHTML = "You have chosen " + y; } function alternative2() {y = x + 10; document.getElementById("demo").innerHTML = "You have chosen "+ y; } function alternative3() {y = x + 15; document.getElementById("demo").innerHTML = "You have chosen "+ y; } document.getElementById("demo2").innerHTML = y; </script> </body> </html>

about 4 years ago · Santiago Gelvez
3 answers
Answer question

0

No puede acceder a las variables declaradas dentro de una función desde fuera de una función. La variable pertenece solo al ámbito de la función, no al ámbito global.

about 4 years ago · Santiago Gelvez Report

0

No necesitas 3 funciones para esto. Puedes hacerlo con 1.

 <!DOCTYPE html> <html> <body> <button onclick="alternative(this)">5</button> <button onclick="alternative(this)">10</button> <button onclick="alternative(this)">15</button> <p id="demo"></p> <script> function alternative(obj) { document.getElementById("demo").innerHTML = "You have chosen " + obj.innerHTML; } </script> </body> </html>

Feliz aprendizaje

about 4 years ago · Santiago Gelvez Report

0

Es normal que haya cero porque en 'y' hay cero y no se realiza ninguna operación en y.

Espero que esta respuesta te ayude a entender lo que has hecho.

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!