簡體   English   中英

jQuery函數(切換img的src attr)

[英]jQuery function (toggling src attr of the img)

我有點不熟悉所有JS東西,但今天我需要使用一些jQ魔術,並且閱讀了幾篇文章,這是我的工作:

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

一切正常,但我需要使其切換。 此功能的基本思想是更改用戶單擊的圖像的src(只需在路徑中添加“ / full”),如果再次單擊已修改的圖像,則從路徑中刪除“ / full”。

我真的不知道該怎么做。 感謝您的任何幫助。

一種方法:

$( '.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;
});

活動委托:

$( '#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;
});

其中#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');
})

您可以使用類切換。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM