Вопрос

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'});
});
Это было полезно?

Решение

Isn'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(){
 ...
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top