Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

160
Vistas
How to make a JavaScript function more concise?

I'm new to StackOverflow and needed some help with the following JavaScript, jQuery question.

Is there a more concise way to code the following?:

jQuery(document).ready(function () {
$("#article1").click(function(){
    showarticleDescription(id=1);
})

$("#article2").click(function(){
    showarticleDescription(id=2);
})

$("#article3").click(function(){
    showarticleDescription(id=3);
})

$("#article4").click(function(){
    showarticleDescription(id=4);
})

$("#article5").click(function(){
    showarticleDescription(id=5);
})
})
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

We can use the starts with CSS selector:

$('[id^="article"]').click(function() {
  showarticleDescription(+this.id.substr(this.id.length - 1));
});

It'd be better though to apply a common class here (and possibly use a custom attribute). In the HTML you can do something like:

<div data-article="1" class="article">...</div>
<div data-article="2" class="article">...</div>
<div data-article="3" class="article">...</div>
$("article").click(function() {
  const article = +$(this).data("article");
  showarticleDescription(article);
});
about 4 years ago · Juan Pablo Isaza Denunciar

0

Add classes and data attributes to your elements (rather than relying on ids) and use event delegation to capture the click events as they "bubble up" the DOM, and then call the function.

function showarticleDescription() {
  console.log($(this).data('id'))
}

$(document).ready(function () {
  $(document).on('click', '.article', showarticleDescription);
});
.article:hover { cursor: pointer; color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-id="1" class="article">One</div>
<div data-id="2" class="article">Two</div>
<div data-id="3" class="article">Three</div>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda