add various “rel” attributes to fancybox galleries

♀尐吖头ヾ 提交于 2019-12-13 05:29:46

问题


i have a page with 4 fancybox (v.2) gallerys, and when i click trough the first gallery he circles through ALL galleries on the page, that's bad. so i want to give each gallery a different "rel" attribute (rel="gallery1", rel="gallery2", rel="gallery3" ...). so i need to count these gallerys and give them the number. my code:

$(document).ready(function() {
$(".fancybox")
    .attr('rel', 'gallery')
    .fancybox({
        openEffect  : 'none',
        closeEffect : 'none',
        padding : 0,
        loop : false
});

});


回答1:


Assuming each gallery is in a <div class="post"> like:

<!-- first gallery -->
<div class="post">
    <a class="fancybox">...</a>
    <a class="fancybox">...</a>
</div>

<!-- second gallery -->
<div class="post">
    <a class="fancybox">...</a>
    <a class="fancybox">...</a>
</div>

You simply need to use .each( function(index, element) ) to loop over the .post elements. Use each .post index to build the gallery identifier, and use each .post element as a jQuery selector context when selecting your .fancybox elements:

$(document).ready(function() {
    $(".post").each(function(idx, elm) {
        $(".fancybox", elm)
            .attr('rel', 'gallery' + idx)
            .fancybox({
                // ...
            });
    });
});
...

$(".fancybox", elm) tells jQuery to look for elements with the fancybox class, but only match elements that are descendants of elm (here, the current .post element for the .each loop).

Depending on how fancybox works, you might be able to move the .fancybox() call outside of the each:

$(".post").each(function(idx, elm) {
    // assign `rel` values as above...
});

$(".fancybox").fancybox({
    // ...
});


来源:https://stackoverflow.com/questions/20802062/add-various-rel-attributes-to-fancybox-galleries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!