2011-09-23 74 views
2

我有點不熟悉JS的所有東西和所有東西,但今天我需要使用一些jQ的魔法,我讀了幾篇文章,這裏是我所做的:jQuery函數(切換IMG的src attr)

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

一切正常,但我需要使它切換。這個功能的基本思想是改變圖像用戶點擊的src(只需在路徑中添加一個「/ full」),如果再次點擊已經修改的圖像,從路徑中刪除「/ full」。

我真的不知道該怎麼做。 感謝您提前提供任何幫助。

回答

3

一種方式做到這一點:

$('.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">元素。

+0

謝謝你,先生!一切都完美無缺! –

+0

@ Adiost666是否有多個這樣的圖像?如果是的話,考慮事件代表團... –

+0

有幾十個,但一切工作非常快,順利,正如計劃,我不認爲改變工作腳本中的任何東西是一個好主意,但我會感激一點你的觀點的解釋(什麼是事件代表團?) –

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

由於某些原因,此代碼不起作用。單擊圖像時根本沒有任何反應。 –

+0

我盲目編碼,所以錯字不會讓我感到驚訝。 –

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

您可以使用一個類切換。