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
Pasar una variable de cadena a un parámetro de función en Javascript

Tengo una docena de campos desencadenantes en una página web que me gustaría consolidar. Estoy intentando agregar un atributo de 'objetivo de datos' a las etiquetas HTML que tienen detectores de eventos que corresponderán al objeto dom de destino para revelar cuando se seleccione.

 var target = this.getAttribute('data-target'); document.querySelector('#${target}');

En este caso, quiero seleccionar el objeto dom con el ID que coincide con el objetivo de datos de la variable. ¿Es posible usar literales de cadena como este en Javascript?

 schedule_yes.addEventListener('focus', handleReveal); function handleReveal(target){ var target = this.getAttribute('data-target'); console.log(target); let what_date = document.querySelector('#${target}'); console.log(what_date); <input class="form-check-input check" type="radio" name="is_schedule" id="schedule_yes" data-target="schedule_date"/>
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Use una plantilla literal en lugar de comillas simples:

 function handleReveal(target){ var target = this.getAttribute('data-target'); console.log(target); var what_date = document.querySelector(`#${target}`); console.log(what_date); }
about 4 years ago · Juan Pablo Isaza Report

0

Nombrar su target de parámetro solo para sobrescribirlo dentro de su función no tiene ningún sentido. Además, para acceder a los atributos de datos, el elemento DOM tiene una propiedad de conjunto de dataset diseñada específicamente para ese propósito.

Así que aquí está la versión limpia:

 function handleReveal(){ const { target } = this.dataset; // same as: const target = this.dataset.target; // same as: const target = this.getAttribute('data-target'); console.log(target); const what_date = document.getElementById(target); console.log(what_date); } schedule_yes.addEventListener('focus', handleReveal);
 <input class="form-check-input check" type="radio" name="is_schedule" id="schedule_yes" data-target="schedule_date"/> <div id="schedule_date">The TARGET</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!