Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 699
LilacEilim Avatar asked Jan 19 '26 02:01

LilacEilim


1 Answers

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>
like image 155
Carsten Løvbo Andersen Avatar answered Jan 20 '26 18:01

Carsten Løvbo Andersen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!