简体   繁体   中英

jQuery - select groups of child elements based on the parent DIV element

I have a normal html page with stuff like divs and links with images:

<div>
  <a href="foo.jpg"> ... </a>
  <a href="boo.jpg"> ... </a>
</div>

<div>
  <a href="bah.jpg"> ... </a>
  <a href="gah.jpg"> ... </a>
</div>

...

I'm trying to hook a lightbox script on all links that end with jpg/gif/png extensions.

Right now, based on a previous question I asked :), I have:

 $('div a').filter(function(){
   return this.href.match('[\.jpg|\.png|\.gif]$');
 }).colorbox({
   rel: 'gallery'
 });

which groups all links inside gallery .

But I would want to group links from each div inside their own gallery. For example .foo' & .boo links inside a gallery1 and .bah & .gah inside gallery2 and so on...

How can I do that?

$('div').each(function(index) {
   $(this).find('a').filter(function(){
       return this.href.match('[\.jpg|\.png|\.gif]$');
   }).colorbox({
       rel: 'gallery' + index
   });
});

(sorry, can't comment on the other answer)

Your regex needs parentheses, not brackets:

(\\.jpg|\\.png|\\.gif)$

otherwise you're literally matching the characters .jpgpnif| and a filename of foo| matches.

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