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

147
Views
Interferencia al emparejar <input> con DOM

HTML:

 <h1 id="ws-title"></h1> <time datetime="" id="ws-date"></time>

JS:

 inp1 = document.querySelector("input[name='ws-date']"); out1 = document.querySelector("#ws-date"); inp1.addEventListener("input", e => { out1.textContent=e.target.value; }); inp2 = document.querySelector("input[name='ws-title']"); out2 = document.querySelector("#ws-title"); inp2.addEventListener("input", e => { out2.textContent=e.target.value; });

Funciona como se esperaba (es decir: cambiar los cambios de entrada correspondientes h2).

Sin embargo:

 function pairListen(name) { inp = document.querySelector(`input[name='${name}']`); out = document.querySelector(`#${name}`); inp.addEventListener("input", e => { out.textContent=e.target.value; }); } pairListen("ws-title"); pairListen("ws-date");

Hace que se cambie <h2 id="ws-date"> cuando se cambia <input name="ws-title"> y viceversa.

¿Porqué es eso? La única diferencia es que el código repetido está incrustado en una función.

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

0

Esto se debe a que cuando declara una variable sin un declarador (es decir, var , let o const ), se define automáticamente en window , this y globalThis (haciendo que ese tipo de variables sean globales , accesibles en cualquier parte de su código). La segunda vez que haces varName = "value"; , no está redeclarando la variable. Lo estás modificando. Puede resolver esto aplicando un declarador.

 function pairListen(name) { const inp = document.querySelector(`input[name='${name}']`); const out = document.querySelector(`#${name}`); inp.addEventListener("input", e => { out.textContent=e.target.value; }); } pairListen("ws-title"); pairListen("ws-date");
 <h1 id="ws-title"></h1> <input name="ws-title" /> <h2 id="ws-date"></h2> <input name="ws-date" />

Moraleja de la historia: siempre declare variables con declaradores, o encontrará resultados sin precedentes. Puedes obligarte a seguir un buen estilo agregando "use strict"; en la parte superior de todos sus archivos JavaScript, que no tolerarán la escritura de código que le dará resultados inesperados.

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!