简体   繁体   中英

jQuery Image Change - Gallery View

I have a large image in a gallery that needs to change when one of the thumbnails is clicked within a unordered list below. The images are coming in dynamically so the jquery script needs to be able to take the src of the thumbnail, remove "-thumb" from the filename, and then replace the large image with the new source.

Please let me know what is my best approach to a gallery like this.

Thanks in advance.

-B

Something like:

$('img.thumb').click(function() {
    var src = $(this).attr('src');
    $('#bigImage').attr('src', src.replace(/-thumb/,''));
});

The below examples apply if your thumbs are being loaded in via ajax:

(1) Using Events/live :

$('img.thumb').live("click", function() {
    var src = $(this).attr('src');
    $('#bigImage').attr('src', src.replace(/-thumb/,''));
});

(2) As a callback to one of jQuery's ajax methods (eg):

function initThumbs()
{
    $('img.thumb').click(function() {
        var src = $(this).attr('src');
        $('#bigImage').attr('src', src.replace(/-thumb/,''));
    });
}

$('#thumbsDiv').load('thumbs.php?p=2', initThumbs);

karim79's answer could be shortened slightly:

$('img.thumb').click(function() {
    $('#bigImage').attr('src', $(this).attr('src').replace(/-thumb/,''));
});

But otherwise, good answer!

The only addition to karim79's is:

In a case the thumbnails are placed within same parent binding an event on that parent would be much better (elegant?) solution that binding events on all thumbnails. The event is propagated, so you can find thumbnails by checking event target.

$().ready(function() {

    //get all images from unordered list and apply click function
    $('ul#myList img').each(function() {
        $(this).click(function() {
            $('#mainImage').attr('src', $(this).attr('src').replace('-thumb', ''));
        });
    });

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM