简体   繁体   English

jQuery函数(切换img的src attr)

[英]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: 我有点不熟悉所有JS东西,但今天我需要使用一些jQ魔术,并且阅读了几篇文章,这是我的工作:

$('.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. 此功能的基本思想是更改用户单击的图像的src(只需在路径中添加“ / full”),如果再次单击已修改的图像,则从路径中删除“ / full”。

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. 其中#images选择包含所有图像的<div id="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. 您可以使用类切换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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