我正在爲客戶端的自定義jQuery燈箱解決方案。我使用數據屬性來創建關係圖像(與fancybox會做的一樣)。在燈箱附近,我重置變量,以便下次打開圖庫時,我的索引將爲0(這決定了是否顯示上一個/下一個按鈕)。jQuery創建重複變量
奇怪的是,下一次我打開一個畫廊並點擊下一個圖標時,控制檯顯示了變量currentIndex的2個值。並在關閉它並打開第三個圖庫時,它會顯示3個可變currentIndex值。
任何想法如何解決這個問題?
<script type="text/javascript">
function centerGalleryOverlay(){
var top = ($('.image-container').height()/2).toFixed() ;
$('.image-container').css('marginTop', '-' + top + 'px');
var left = ($('.image-container').width()/2).toFixed() ;
$('.image-container').css('marginLeft', '-' + left + 'px');
}
$(document).ready(function(){
var galleryTitle = null;
$('.cm-gallery').click(function(e){
e.preventDefault();
galleryTitle = $(this).data('gallery');
$('.gallery-overlay .image-container img').attr('src', $(this).attr('href'));
$('.gallery-overlay').fadeIn(500);
centerGalleryOverlay();
var galleryItems = null;
galleryItems = [];
$('.cm-gallery').each(function(){
if($(this).data('gallery') == galleryTitle){
galleryItems.push($(this).attr('href'))
}
});
var currentIndex = null;
currentIndex = 0;
if(galleryItems.length > 0){
$('.gallery-overlay .image-container .gallery-next').show();
}
$('.gallery-overlay .image-container .gallery-next').click(function(){
currentIndex = currentIndex + 1;
console.log(currentIndex);
if(currentIndex >= (galleryItems.length - 1)){
$('.gallery-overlay .image-container .gallery-next').hide();
}
$('.gallery-overlay .image-container .gallery-prev').show();
$('.gallery-overlay .image-container img').attr('src', galleryItems[currentIndex]);
})
$('.gallery-overlay .image-container .gallery-prev').click(function(){
currentIndex = currentIndex - 1;
console.log(currentIndex);
if(currentIndex <= 0){
$('.gallery-overlay .image-container .gallery-prev').hide();
}
$('.gallery-overlay .image-container .gallery-next').show();
$('.gallery-overlay .image-container img').attr('src', galleryItems[currentIndex]);
})
})
$('.gallery-overlay .gallery-close').click(function(){
$('.gallery-overlay').hide();
galleryItems = null;
currentIndex = null;
galleryTitle = null;
});
})
</script>
請粘貼相關代碼 - 只要目標更改,外部鏈接將使您的問題無關緊要。 – technophobia
[我的網站或項目中的某些內容不起作用。我可以只粘貼一個鏈接嗎?](https://meta.stackoverflow.com/questions/254428/something-in-my-web-site-or-project-doesnt-work-can-i-just-paste -a-link-to-it) –
表示歉意,現在在這裏有源碼 –