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

298
Views
¿Existe una forma más sencilla de escribir esta instrucción if/else sin una variable?

Tengo una prueba con una entrada. A la primera pulsación de enter, califica la respuesta. En la segunda pulsación de entrada, restablece una nueva pregunta.

  1. ¿Hay una forma más sencilla de escribir esto sin la variable flip ?

  2. Si no, ¿hay alguna forma de incluir la variable dentro para poder exportar la función como un todo?

 var flip = true; document.getElementById("guess-input").addEventListener("keyup", (event) => { if (event.key === "Enter") { event.preventDefault(); if (flip === true) { flip = false; check(); } else { flip = true; reset(); } } });
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Puede usar un atributo de datos o una clase

 document.getElementById("guess-input").addEventListener("keyup", (event) => { if (event.key === "Enter") { event.preventDefault(); const tgt = event.target; if (tgt.matches(".flipped")) check(); else reset(); tgt.classList.toggle("flipped") } });
about 4 years ago · Juan Pablo Isaza Report

0

Podemos divertirnos un poco y establecer un nuevo oyente al final del primero, mientras hacemos que nuestros oyentes se ejecuten solo una vez.

 const input = document.getElementById("guess-input") // to keep it neat const options = {once: true} function checker(e){ if (e.key !== 'Enter') return e.preventDefault(); check(); input.addEventListener('keyup', resetter, options); } function resetter(e) { if (e.key !== 'Enter') return e.preventDefault(); reset(); input.addEventListener('keyup', checker, options); } input.addEventListener("keyup", checker, options)

También puede hacerlo reasignando el controlador onkeyup que sobrescribe la devolución de llamada original:

 const input = document.getElementById("guess-input") // to keep it neat function checker(e){ if (e.key !== 'Enter') return e.preventDefault(); check(); input.onkeyup = resetter; } function resetter(e) { if (e.key !== 'Enter') return e.preventDefault(); reset(); input.onkeyup = checker; } input.onkeyup = checker;

Esto es sólo un enfoque diferente al problema. El enfoque de atributos de datos es perfectamente válido.

about 4 years ago · Juan Pablo Isaza Report

0

Si quisiera mantener el código igual, podría usar un cierre : esencialmente mueva su variable dentro de la función pero haga que esa función devuelva una nueva función a la que llama el oyente cuando se activa el evento. Esto funciona porque la función devuelta lleva consigo referencias a su "entorno léxico externo" que, en este caso, es la variable flip .

 export default function guesser() { let flip = true; return function (event) { if (event.key === "Enter") { event.preventDefault(); if (flip === true) { flip = false; check(); } else { flip = true; reset(); } } } });

Y luego en tu código principal:

 import guesser from './guesser'; const el = document.getElementById('guess-input'); // Call the guesser function which returns that inner // function which the listener calls when the event is triggered el.addEventListener('keyup', guesser());
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!