简体   繁体   中英

Storing multiple selectors in a single variable

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(){
 ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM