2016-04-01 6 views
1

Я пытаюсь настроить лайтбокс плагин JQuery под названием LightGallery для достижения следующего результата:JQuery триггер («щелчок») работает только один раз

1- Сделать сценарий извлечь все изображения из папки, используя приращение индекса как путь изображения;

2- Сделать лайтбоксом открытым после нажатия на другой элемент.

Проблема заключается в том:

Плагин открывает только осветителя один раз!.

Я использую trigger('click'), чтобы запустить его в первый раз, но после его закрытия и попытки щелкнуть, чтобы повторить его снова, он НЕ работает.

плагин выглядит разрушенным и открывается только одно изображение!

Я хочу, чтобы он открывал лайтбокс каждый раз, когда я нажимаю на целевые элементы.

Вот мои попытки: (Pen here)

$(document).ready(function() { 
 

 
    var $lg = $('#lightgallery'); 
 

 
    function fetchFolderImages() { 
 
    var checkImages, endCheckImages; 
 
    var img; 
 
    var imgArray = new Array(); 
 
    var i = 1; 
 

 
    var myInterval = setInterval(loadImage, 1); 
 

 
    if ($lg.children().length > 0) { 
 
     checkImages = false; 
 
     endCheckImages = true; 
 
    } else { 
 
     checkImages = true; 
 
     endCheckImages = false; 
 
    } 
 

 
    function loadImage() { 
 
     if (checkImages) { 
 
     checkImages = false; 
 
     img = new Image(); 
 
     img.src = 'http://sachinchoolur.github.io/lightGallery/static/img/' + i + '.jpg'; 
 
     img.onload = moreImagesExists; 
 
     img.onerror = noImagesExists; 
 
     } 
 
     if (endCheckImages) { 
 
     clearInterval(myInterval); 
 
     console.log('function [loadImage] done'); 
 
     runLightGallery(); 
 
     return; 
 
     } 
 
    } 
 

 
    function moreImagesExists() { 
 
     imgArray.push(img); 
 
     $lg.append($('<a/>', { 
 
     'href': img.src 
 
     }).html(img)); 
 
     i++; 
 
     checkImages = true; 
 

 
     console.log('function [moreImagesExists] done'); 
 
    } 
 

 
    function noImagesExists() { 
 
     endCheckImages = true; 
 

 
     console.log('function [noImagesExists] done'); 
 
    } 
 

 
    console.log('function [fetchFolderImages] done'); 
 
    } 
 

 
    function runLightGallery() { 
 

 
    if ($lg.lightGallery()) { 
 
     //alert('working'); 
 
    } else { 
 
     //alert('destroyed'); 
 
     $lg.lightGallery({ 
 
     thumbnail: true 
 
     }); 
 

 
    } 
 
    //trigger click event on image to open the lightbox 
 
    $lg.children('a').trigger('click'); 
 

 
    //empty method, thought we may can use 
 
    $lg.on('onAfterOpen.lg', function(event) { 
 
     //maybe we can use this method? 
 
    }); 
 

 
    $lg.on('onCloseAfter.lg', function(event) { 
 
     $lg.children().remove(); 
 
     $lg.toggle(); 
 
     //$lg.lightGallery().destroy(true); 
 
    }); 
 

 
    console.log('function [runLightGallery] done'); 
 

 
    } 
 

 
    $('.gallery-item').each(function() { 
 
    $(this).on('click', function() { 
 
     $lg.toggle(); 
 
     fetchFolderImages(); 
 
    }); 
 
    }); 
 

 
});
<!DOCTYPE html> 
 
<html> 
 

 
<head> 
 
    <link type="text/css" rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/lightgallery/1.2.16/css/lightgallery.css" /> 
 
</head> 
 

 
<body> 
 

 
    <div class="gallery"> 
 
    <div class="gallery-item">Gallery Item 1</div> 
 
    <div class="gallery-item">Gallery Item 2</div> 
 
    <div class="gallery-item">Gallery Item 3</div> 
 
    </div> 
 

 
    <div id="lightgallery" style="display: none; border: 5px solid red"></div> 
 

 
    <!--============== scripts ==============--> 
 
    <!-- jQuery --> 
 
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.js"></script> 
 
    <!-- jQuery mouse wheel --> 
 
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.13/jquery.mousewheel.js"></script> 
 
    <!-- lightGallery : a lightbox jQuery plugin --> 
 
    <script src="//cdnjs.cloudflare.com/ajax/libs/lightgallery/1.2.16/js/lightgallery.js"></script> 
 
    <!-- lightGallery plugin for thumbnails --> 
 
    <script src="//cdnjs.cloudflare.com/ajax/libs/lightgallery/1.2.16/js/lg-thumbnail.js"></script> 
 

 
</body> 
 

 
</html>

ответ

2

LightGallery должен быть разрушен и вновь инициализированы

Чтобы уничтожить LightGallery использовать этот код $lg.data('lightGallery').destroy(true);

источник: https://github.com/sachinchoolur/lightGallery/issues/238#issuecomment-161020492

Pen

$(document).ready(function() { 
 

 
    var $lg = $('#lightgallery'); 
 

 
    function fetchFolderImages() { 
 
    var checkImages, endCheckImages; 
 
    var img; 
 
    var imgArray = new Array(); 
 
    var i = 1; 
 

 
    var myInterval = setInterval(loadImage, 1); 
 

 
    if ($lg.children().length > 0) { 
 
     checkImages = false; 
 
     endCheckImages = true; 
 
    } else { 
 
     checkImages = true; 
 
     endCheckImages = false; 
 
    } 
 

 
    function loadImage() { 
 
     if (checkImages) { 
 
     checkImages = false; 
 
     img = new Image(); 
 
     img.src = 'http://sachinchoolur.github.io/lightGallery/static/img/' + i + '.jpg'; 
 
     img.onload = moreImagesExists; 
 
     img.onerror = noImagesExists; 
 
     } 
 
     if (endCheckImages) { 
 
     clearInterval(myInterval); 
 
     console.log('function [loadImage] done'); 
 
     runLightGallery(); 
 
     return; 
 
     } 
 
    } 
 

 
    function moreImagesExists() { 
 
     imgArray.push(img); 
 
     $lg.append($('<a/>', { 
 
     'href': img.src 
 
     }).html(img)); 
 
     i++; 
 
     checkImages = true; 
 

 
     console.log('function [moreImagesExists] done'); 
 
    } 
 

 
    function noImagesExists() { 
 
     endCheckImages = true; 
 

 
     console.log('function [noImagesExists] done'); 
 
    } 
 

 
    console.log('function [fetchFolderImages] done'); 
 
    } 
 

 
    function runLightGallery() { 
 

 
    if ($lg.lightGallery()) { 
 
     //alert('working'); 
 
    } else { 
 
     //alert('destroyed'); 
 
     $lg.lightGallery({ 
 
     thumbnail: true 
 
     }); 
 

 
    } 
 
    //trigger click event on image to open the lightbox 
 
    $lg.children('a').trigger('click'); 
 

 
    //empty method, thought we may can use 
 
    $lg.on('onAfterOpen.lg', function(event) { 
 
     //maybe we can use this method? 
 
    }); 
 

 
    $lg.on('onCloseAfter.lg', function(event) { 
 
     $lg.children().remove(); 
 
     $lg.toggle(); 
 
     $lg.data('lightGallery').destroy(true); 
 
    }); 
 

 
    console.log('function [runLightGallery] done'); 
 

 
    } 
 

 
    $('.gallery-item').each(function() { 
 
    $(this).on('click', function() { 
 
     $lg.toggle(); 
 
     fetchFolderImages(); 
 
    }); 
 
    }); 
 

 
});
<html> 
 

 
<head> 
 
    <link type="text/css" rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/lightgallery/1.2.16/css/lightgallery.css" /> 
 
</head> 
 

 
<body> 
 

 
    <div class="gallery"> 
 
    <div class="gallery-item">Gallery Item 1</div> 
 
    <div class="gallery-item">Gallery Item 2</div> 
 
    <div class="gallery-item">Gallery Item 3</div> 
 
    </div> 
 

 
    <div id="lightgallery" style="display: none; border: 5px solid red"></div> 
 

 
    <!--============== scripts ==============--> 
 
    <!-- jQuery --> 
 
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.js"></script> 
 
    <!-- jQuery mouse wheel --> 
 
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.13/jquery.mousewheel.js"></script> 
 
    <!-- lightGallery : a lightbox jQuery plugin --> 
 
    <script src="//cdnjs.cloudflare.com/ajax/libs/lightgallery/1.2.16/js/lightgallery.js"></script> 
 
    <!-- lightGallery plugin for thumbnails --> 
 
    <script src="//cdnjs.cloudflare.com/ajax/libs/lightgallery/1.2.16/js/lg-thumbnail.js"></script> 
 

 
</body> 
 

 
</html>

+0

Спасибо Аммар, я ценю это! :) – Homer

0

Я быстро просмотрел свой код и увидел, что вы загружаете динамические данные Попробуйте даже делегацию, https://learn.jquery.com/events/event-delegation/ Проблема заключается в том, что на момент привязки события, а не все элементы «а», реально существующие для привязки события к нему

Ваше запускающее событие должно быть что-то вроде

$(document).on('click','#someId a:first-child',function(){ 

}) 
1

Вы не уничтожаете LightGallary правильным способом.

Используйте это для 'onCloseAfter.lg' событие:

$lg.on('onCloseAfter.lg', function(event) { 
    $lg.children().remove(); 
    $lg.toggle(); 
    //$lg.lightGallery().destroy(true); 
    $lg.data('lightGallery').destroy(true); 
}); 
+0

Большое спасибо Мохамеду, я ценю это! :) – Homer