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

179
Vistas
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 Respuestas
Responde la pregunta

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 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