jQuery image slide show carousel when using ajax

2019-08-20 06:02发布

问题:

I've been trying to build an image slide show / carousel using jQuery, and came across colorbox which I thing is really good, and does things the way I want to.

I'm stuck with how to build a slide show of images when using the ajax method they have.

I have six images per item that i'd like to load from the server, and run as a slideshow / carousel just like you see them when you click on the first link on this page under Elastic Transition.

I've succeeded in getting the images to the script using ajax, but i don't end up with a slide show. How can I do this? I currently end up with all the images below each other, and no forward or backward buttons etc.

Can you help?

HTML

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'/>
    <link rel="stylesheet" href="colorbox.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="../jquery.colorbox.js"></script>
    <script>
        $(document).ready(function(){
            $(".ajax").colorbox();
        });
    </script>
</head>
<body>
    <p><a class='ajax' href="../content/ajax.html">Outside HTML (Ajax)</a></p>
</body>
</html>

ajax.html (pulls images and returns it to the script

<div>
    <img class="gallery" src='/slide/content/ohoopee1.jpg'>
    <img class="gallery" src='/slide/content/ohoopee2.jpg'>
    <img class="gallery" src='/slide/content/ohoopee3.jpg'>
</div>

I just could not figure what to do more.

Desired

回答1:

I would recommend using ajax to add the markup to your document, then assign and open Colorbox to those elements.

An example would be something like this:

<div id='pictures' style='display:none'></div>
<script>
    $('.ajax').on('click', function(e){
        e.preventDefault();
        $.ajax(this.href, {
            success: function(html) {
                $('#pictures').html(html).find('img').colorbox({href: function(){
                    return this.src;
                }, open:true});
            }
        });
    });
</script>