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

171
Vistas
Can I use variables somehow with .on Jquery

I have 3 buttons inside one div and I want to add the same click listener to all of them. I have a few actions on those buttons so I first keep them as variables in the begging of the function and then I want to add the on listener, using those variables. Is there any way? The HTML looks like this:

<div class="wrapper">
    <button class="a"></button>
    <button class="b"></button>
    <button class="c"></button>
</div>

The JS:

var $wrapper = $('.wrapper'),
    $aBtn = $wrapper.find('.a'),
    $bBtn = $wrapper.find('.b'),
    $cBtn = $wrapper.find('.c');

//The working but less neat solution
$('.wrapper .a, .wrapper .b, .wrapper .c').on('click', func);

//What I want
($aBtn, $bBtn, $cBtn).on('click', func);
about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

You can use .add() // Ref link

var $wrapper = $('.wrapper'),
    $aBtn = $wrapper.find('.a'),
    $bBtn = $wrapper.find('.b'),
    $cBtn = $wrapper.find('.c');

//What I want
$($aBtn).add($bBtn).add($cBtn).on('click', func);

function func(){alert($(this).attr("class"))}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
    <button class="a">a</button>
    <button class="b">b</button>
    <button class="c">c</button>
</div>

about 4 years ago · Santiago Trujillo Denunciar

0

Using add function

$aBtn.add($bBtn,$cBtn).on('click', func);
about 4 years ago · Santiago Trujillo Denunciar

0

The following code doesn't use variables, but you can sometimes simply bind events on selectors that wraps multiple elements

$('.wrapper button').on('click', func);

With this code, each button has an event handler attached to it. When you click an element, this reference the element like showcased in this jsfiddle : https://jsfiddle.net/3uwx15vg/1/

As an alternative to variables, you can even chain event handlers

$('.wrapper button').on('click', func).on('blur', func);
about 4 years ago · Santiago Trujillo 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