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

180
Visualizações
How to consolidate 2 functions into a single one (Use one function to target multiple classes)

I have 2 functions doing the same thing, just targeting two different classes on my page. Is there a way to consolidate these two into a single function?

$(document).on("click", ".class1", function(event) {
      const $this = $(this);
      if ($this.find($(event.target).closest("a")[0]).length === 0) {
          event.preventDefault();
          $this.find("a")[0].click();
      }
  });

  $(document).on("click", ".class2", function(event) {
      const $this = $(this);
      if ($this.find($(event.target).closest("a")[0]).length === 0) {
          event.preventDefault();
          $this.find("a")[0].click();
      }
  });

I have a lot of cards on the page that have the class1 and class2 name, I know I can give them each an extra class something like .clickable and add it to every single card on the page, but I was wondering if there's an easier way to just have this function target 2 classes at once.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can put them together like this

to activate the anchor link on the first matching <a> element

$(document).on("click", ".class1, .class2", function(event) {
  if ($(this).find($(event.target).closest("a")[0]).length === 0) {
          event.preventDefault();
          $(this).find("a")[0].click();
      }
     // $(event.target).find("a").eq(0)[0]?.click();
});
.padd {
  padding: 30px;
  background: #f0f0f0;
  margin-bottom: 20px;
}

#gohere{
margin-top:500px;
height:300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='class1 padd'>
  <a href='#gohere' onclick='console.log("CLICKED1")'>the link</a><br>
  <a href='#' onclick='console.log("this should not fire....")'>a second link</a>
</div>

<div class='class2 padd'>
  <a href='#' onclick='console.log("CLICKED2")'>the link</a>
</div>


<div class='class2 padd'>
  no link here
</div>


<div id='gohere'>Anchor link text....</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