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 clicke开发者_如何学God 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.
精彩评论