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

206
Views
JQuery eficiente para obtener un valor de atributo

Supongamos que tengo algo de HTML con un atributo data-*:

 <div data-my-attribute="something"></div>

Ahora, tengo algo de JavaScript que quiere hacer algo si ese atributo existe. Pero ese JavaScript también necesita el valor (si existe el atributo). Entonces, puedo hacer algo como esto:

 var value = $('[data-my-attribute]').attr('data-my-attribute'); if (value) { do something }

Que el nombre del atributo aparezca dos veces en este código simplemente me molesta. Podría hacer algo tonto como esto para tener solo un lugar donde se declare el nombre del atributo, pero el código es más detallado y menos legible:

 var attrName = "data-my-attribute"; var value = $(`[${attrName}]`).attr(attrName); if (value) { do something }

¿Existe una forma mejor (más simple, que no implique especificar el nombre del atributo dos veces) para encontrar y recuperar el valor de un atributo en un fragmento de HTML?

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