Reputation: 129
Trying to create multiple listeners with a loop. How to make it work?
var buttons = ['one', 'two', 'tree'];
$.each(keys, function(key, value) {
$(value).click(function() {
// do something
});
});
Also, is there a shortcut to not writing key, value
when I only need the value?
Upvotes: 3
Views: 1603
Reputation: 24590
In jQuery you can select some elements together, and seperate them using colon ,
var buttons = ['one', 'two', 'tree'];
$(buttons.join()).click(function(){
// Do something
})
In this example I'm using join to convert the array to one,two,three
then I add one event listener to all those element
Upvotes: 0
Reputation: 308
You are better off putting a delegated event listener on a parent instead of iterating through every button. For example, if you place all your <button>
elements inside of a <div>
with the id #container
, then you can write your listener like this:
$('#container').on('click', 'button', function() {
// do something;
});
Now, every time a button element is clicked within that div, your callback will be invoked. You can also use a class selector in place of 'button'
to only listen to elements that have that class.
Upvotes: 1
Reputation: 2219
If you want to make it work by looping then you can use
var buttons = ['.one', '.two', '.three'];
// ---------------- with -------- $.each();
$.each( buttons, function(key, value) {
$(value).click(function() {
// ------------- Do something
});
});
// ------------------ with ----------- for loop
for( var i=0 ; i < buttons.length ; i++ )
{
$(buttons[i]).click(function({
// ------------- Do something
});
}
But why to go this round if just want to assign event
$('.one, .two, .three, #one, #two, #three').click(function() {
// ------------- Do something
});
OR if having variable
var buttons = '.one, .two, .three, #one, #two, #three';
$(buttons).click(function() {
// ------------- Do something
});
AND THATS IT no key, no value, no for, no each
Upvotes: 1
Reputation: 160
Sounds like you'd be better off assigning the click handler to a button with a specific class name instead of iterating over a list of selectors and assigning a new function inside a loop.
<button class='my-button' id="one">
One
</button>
<button class='my-button' id="two">
Two
</button>
<button class='my-button' id="three">
Three
</button>
and the JS
$('.my-button').click(function() {
var id = $(this).attr('id');
$('body').append("<div>Button " + id + " was clicked</div>");
});
Take a look this fiddle https://jsfiddle.net/4e7rk10L/
Upvotes: 0
Reputation: 24590
If you really want loop (This was your question) you can do this:
for(var i=0;i<buttons.length;i++)
$(buttons[i]).click(function({
// Do something
})
Upvotes: -1