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

138
Views
¿Por qué esta función funciona solo en el segundo clic?

Tengo una función simple que oculta el texto al hacer clic. Sin embargo, solo funciona con el segundo clic. Intenté reformular la declaración condicional pero nada ha funcionado hasta ahora. jsfiddle https://jsfiddle.net/Montinyek/293hmpu1/18/

 let btn = document.getElementById('btn'); let hello = document.getElementById('hello'); function test() { if (hello.style.display !== 'block') { hello.style.display = 'block'; } else { hello.style.display = 'none'; } } btn.addEventListener('click', test)
 <div id='hello'> hello </div> <div id='btn'> button </div>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Al principio, nada ha establecido el estilo, por lo que la prueba !=='block' será verdadera. Y luego configura el estilo para bloquear, por lo que necesita otro clic para que no quede en ninguno.

Si configura las cosas al revés, funcionará porque el estilo no está configurado en ninguno, por lo que inmediatamente lo configura en ninguno.

La confusión a menudo parece surgir porque la configuración de las propiedades de estilo no está ahí inicialmente, es decir, no se configura hasta que usted las configura.

 let btn = document.getElementById('btn'); let hello = document.getElementById('hello'); function test() { if (hello.style.display !== 'none') { hello.style.display = 'none'; } else { hello.style.display = 'block'; } } btn.addEventListener('click', test)
 <div id='hello'> hello </div> <div id='btn'> button </div>

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!