Opening multiple Fancybox galleries via manual lin

2020-04-10 03:47发布

问题:

I've attempted to convert the solution offered in How do I open fancybox via manual call for a gallery in the html not via the jquery options? in order to apply it to several galleries, but can't get it to function correctly.

What I have is several links with the following attributes:

<a href="#" class="open-album" data-open-id="album-1">Album 1</a>
<a href="#" class="open-album" data-open-id="album-2">Album 2</a>

etc.

These are supposed to apply to their respective Fancybox-enabled albums, for example:

 <a href="#" class="image-show" rel="album-1"><img src="#" /></a>
 <a href="#" class="image-show" rel="album-1"><img src="#" /></a>
 <a href="#" class="image-show" rel="album-1"><img src="#" /></a>

and

 <a href="#" class="image-show" rel="album-2"><img src="#" /></a>
 <a href="#" class="image-show" rel="album-2"><img src="#" /></a>
 <a href="#" class="image-show" rel="album-2"><img src="#" /></a>

Fancybox looks for the .image-show class, and works fine when the images themselves are clicked.

The following jQuery code is supposed to link the album titles to the 1st image in their respective albums:

 $('.open-album').click(function(e) {
    var el, id = $(this.element).data('open-id');
    if(id){
        el = $('.image-show[rel=' + id + ']:eq(0)');
        e.preventDefault();
        el.click();
    }
}); 

As you can see, the goal was to obtain the data-open-id from the album title and use it to open the first Fancybox item with the value as its rel attribute. Alas, it doesn't work. Any ideas on what could be going wrong? Your help would be much appreciated!

Thanks in advance!

回答1:

I assume that you are binding the selector .image-show to fancybox, aren't you?

$(".image-show").fancybox();

if so, the issue with your code is that $(this.element) should be used within fancybox callbacks only, but since you are using a regular jQuery method ( .click() ) then you should refer to the current element like $(this)

$('.open-album').click(function(e) {
    var el, id = $(this).data('open-id');
    if(id){
        el = $('.image-show[rel=' + id + ']:eq(0)');
        e.preventDefault();
        el.click();
    }
}); 

See JSFIDDLE