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

208
Views
Perder el valor de una variable javascript

¿Por qué estoy perdiendo el valor de one variable? Intenté declarar la variable como una variable global y no funcionó. También probé algunos comandos de console.log, pero no entendí qué sucedió.

 function check() { document.addEventListener("DOMContentLoaded", ready); } let one; // 1 function ready() { let button = document.getElementById("transform"); let div = document.getElementById("objectImg"); let img = document.getElementById("dog"); console.log(div); console.log(button); button.addEventListener("click", function(a) { if (img) { img.parentNode.removeChild(img); div.innerHTML = "<img id = 'red' src = 'img/cat.jpg'>"; one = document.getElementById("red"); img = false; console.log(one); // <img id="red" src="img/cat.jpg"> } else { alert("some text"); } }); console.log(one); // undefined // one.addEventListener("mouseover", (a) => { // }); } check();
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

La razón es que está configurando el valor en one dentro de un detector de eventos. El código dentro del detector de eventos se ejecuta después de hacer clic en el botón. Por lo tanto, establezca el valor en one fuera del detector de eventos.

about 4 years ago · Juan Pablo Isaza Report

0

En su código, está llamando al one antes de que se inicie, por lo que, según el código a continuación, puede llamar a la función una vez one se asignan algunos valores a la variable, luego obtendrá el valor.

 let one; (function () { document.getElementById("button").addEventListener("click", function(a) { one = 56 console.log('one from button click event: ' + one) callWhenOneIsSet() }) })() function callWhenOneIsSet() { console.log('one from callWhenOneIsSet: ' + one) }
 <button id="button">Click it</button>

about 4 years ago · Juan Pablo Isaza 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!