I have a piece of code that handles clicks on images that represent buttons. If that image is clicked, its corresponding image will appear to the user. By selecting the multiple IDs of the images, the vode below works perfectly fine.
$("#content").on('click','#buttonID1, #buttonID2, #buttonID3, #buttonID4', function(){
var $varThis = $(this);
var tmpID = $varThis.prop('id').split('ID')[1];
$('#imageID'+tmpID).css({'display': 'block'});
});
However, I will have a lot more of these IDs to select. So is it possible to store the image's #buttonID
in a single variable and place that variable inside the .on()
method? Will they be independently selected?
The code below does not work.
var $buttons = $('#buttonID1, #buttonID2, #buttonID3, #buttonID4');
$("#content").on('click',$buttons, function(){
var $varThis = $(this);
var tmpID = $varThis.prop('id').split('ID')[1];
$('#imageID'+tmpID).css({'display': 'block'});
});
I have a piece of code that handles clicks on images that represent buttons. If that image is clicked, its corresponding image will appear to the user. By selecting the multiple IDs of the images, the vode below works perfectly fine.
$("#content").on('click','#buttonID1, #buttonID2, #buttonID3, #buttonID4', function(){
var $varThis = $(this);
var tmpID = $varThis.prop('id').split('ID')[1];
$('#imageID'+tmpID).css({'display': 'block'});
});
However, I will have a lot more of these IDs to select. So is it possible to store the image's #buttonID
in a single variable and place that variable inside the .on()
method? Will they be independently selected?
The code below does not work.
var $buttons = $('#buttonID1, #buttonID2, #buttonID3, #buttonID4');
$("#content").on('click',$buttons, function(){
var $varThis = $(this);
var tmpID = $varThis.prop('id').split('ID')[1];
$('#imageID'+tmpID).css({'display': 'block'});
});
Share
Improve this question
edited Nov 21, 2012 at 16:53
bfavaretto
71.9k18 gold badges117 silver badges159 bronze badges
asked Nov 21, 2012 at 16:14
NavigatronNavigatron
2,1356 gold badges34 silver badges64 bronze badges
3 Answers
Reset to default 4Isn't this what classes are for? Add a class, let's call it myButton
to all your buttons and then use that as a selector.
$("#content").on('click','.myButton', function(){
Alternatively, if you insist on using ids, this ought to work:
var buttons = '#buttonID1, #buttonID2, #buttonID3, #buttonID4';
$("#content").on('click',buttons, function(){
Change
var $buttons = $('#buttonID1, #buttonID2, #buttonID3, #buttonID4');
To
var $buttons = '#buttonID1, #buttonID2, #buttonID3, #buttonID4';
$("#content").on('click',$buttons, function(){
var $varThis = $(this);
var tmpID = $varThis.prop('id').split('ID')[1];
$('#imageID'+tmpID).css({'display': 'block'});
});
You should use css attribute-starts-with selector for that:
$("#content").on('click','button[id^="buttonID"]', function(){
...
}