lundi 13 juin 2016

Simplify selector with numbered IDs

I have a series of divs on the same page for which I have attached a click function that acts like an <a> tag, directing the user to a URL extracted from a custom data-attribute. My HTML is as follows:

<div id="my-button1" class="button-style-1" data-href="http://www.stackoverflow.com">
  Button
</div>

<div id="my-button2" class="button-style-1" data-href="http://www.w3schools.com">
  Button 2
</div>

and jQuery:

$('#my-button1,#my-button2').click(function() {
    var dataURL = $(this).data('href');
    window.open(dataURL, '_blank');
  });

My question is this, is it possible to simplify the selector to something like:

$('#my-button[i]')

such that it would be much more compact in the event that I have many of these divs contained on the same page? If it is possible, how would I achieve this effect?

jsFiddle: https://jsfiddle.net/shaneswebdevelopment/fLj7y0kz/

Aucun commentaire:

Enregistrer un commentaire