Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

161
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda