2013-01-03 104 views
0

當我單擊圖像時,它會更改爲備用版本(data-other-src)。onclick使用jquery更改圖像源

當我點擊一個圖像,我也想重置所有其他圖像到他們的src。我怎樣才能做到這一點?

這裏是我到目前爲止的代碼:

<script> 
$(".imageOnOff").live('click', function() { 
$(this).attr({src: $(this).attr('data-other-src'),'data-other-src': $(this).attr('src') 
}) 
    }); 
</script> 

<img class="imageOnOff" data-other-src="images/color/1.png" src="images/color/1-1.png"  width="16" height="16"> 
<img class="imageOnOff" data-other-src="images/color/2-2.png" src="images/color/2.png" width="16" height="16"> 
<img class="imageOnOff" data-other-src="images/color/3-3.png" src="images/color/3.png" width="16" height="16"> 
<img class="imageOnOff" data-other-src="images/color/4-4.png" src="images/color/4.png" width="16" height="16"></a> 

回答

0

變化的數據,其他-SRC爲src相反的,你應該存儲原始源:

$(".imageOnOff").live('click', function() { 
    $(".imageOnOff[original-src]").each(function(){ 
     this.src = $(this).attr('original-src'); 
     $(this).removeAttr('original-src'); 
    }); 
    $(this).attr('original-src', this.src); 
    this.src = $(this).data('other-src'); 
})​ 

Demonstration

+0

感謝,但我有此代碼錯誤。 – Efi

+0

對不起。我修正了一個錯誤。參見[示範](http://jsfiddle.net/UfCL3/1/)。 –

+0

自1.6開始,建議使用'$(this).data('otherSrc')'而不是'$(this).data('other-src')'參見http://api.jquery.com/ data /#data-html5 – jantimon