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

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

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

0

Using add function

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

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