问题
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