简体   繁体   中英

How do I select elements with similar attributes using jQuery?

First up, sorry about the title, I know it's not very specific, but I'm really stumped on what else to say.

So before I try and ramble on at what my problem is, you might as well check out this jsfiddle I made: http://jsfiddle.net/ax1ncdmu/2

How it works in this fiddle is exactly how I want it to work, but as you can see the jQuery is like this:

$(document).ready(function () {
  $("input[name=guest0]").click(function () {
    $('#guest0').toggle();
  });
  $("input[name=guest1]").click(function () {
    $('#guest1').toggle();
  });
  $("input[name=guest2]").click(function () {
    $('#guest2').toggle();
  });
});

But it seems pretty sloppy to write out the code like that, just repeating the same thing over again. I feel like it should be obvious but I haven't worked with jQuery before, so I'm having a hard time figuring it out.

Is there a way to figure out the 'name' of the checkbox being clicked and then use that string to plug into the code? Or is that going the wrong way about it?

You can use jQueries attribute-starts-with-selector :

$(document).ready(function () {
  // all inputs that its name starts with "guest"
  $("input[name^=guest]").click(function () {
    // read the name and apply to id
    $('#'+$(this).attr('name')).toggle();
  });
});

See it working:

http://jsfiddle.net/ax1ncdmu/7/

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