简体   繁体   中英

jQuery function (toggling src attr of the img)

I kind of not familiar with all that JS stuff and everything but today I need to use some jQ magic and I read a couple of articles and here's what I've done:

$('.thumb_img').click(function() {
    $(this).attr('src', $(this).attr('src').replace('img/', 'img/full/'));
})

Everything works perfectly but I need to make it toggling. The basic idea of this function is to change the src of the image user clicked (just add a "/full" in the path) and if clicked already modificated image again, delete "/full" from the path.

I really have no idea how to make it. Thanks for any help in advance.

One way to do it:

$( '.thumb_img' ).click( function () {
    var src = this.src;

    if ( src.indexOf( '/full/' ) !== -1 ) {
        src = src.replace( '/full/', '/' ); 
    } else {
        src = src.replace( 'img/', 'img/full/' );
    }

    this.src = src;
});

Event delegation:

$( '#images' ).delegate( '.thumb_img', 'click', function () {
    var src = this.src;

    if ( src.indexOf( '/full/' ) !== -1 ) {
        src = src.replace( '/full/', '/' ); 
    } else {
        src = src.replace( 'img/', 'img/full/' );
    }

    this.src = src;
});

where #images selects the <div id="images"> element that contains all the images.

$('.thumb_img').click(function() {
    //Store your src value so you don't need to get it again.
    var src = $(this).attr('src');
    //Determine whether the image is currently "full"
    var full = src.indexOf('full/') > -1; 
    //If it's full, remove it, otherwise, put it in the src.
    src = full ? src.replace('img/full/', 'img/') : src.replace('img/', 'img/full/');
    //Set your SRC value
    $(this).attr('src', src); 
})
$('.thumb_img').not('.state').click(function() {
    $(this).attr('src', $(this).attr('src').replace('img/', 'img/full/')).toggleClass('.state');
})
$('.thumb_img.state').click(function() {
    $(this).attr('src', $(this).attr('src').replace('img/full/', 'img/')).toggleClass('.state');
})

You can use a class toggle.

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