2012-04-16 56 views
0

我真的很新的JavaScript。我新點擊圖片,該圖片將改變SRC和其他圖片。用JavaScript更改src只有一個在一組圖像

這是代碼:

<a href="#pduno"><img onclick="this.src='img/pduno.png';document.getElementsByClassName('imgdp').src='img/pddos.png'" class="imgdp" src="img/pduno.png" width="13" height="11" /></a> 
<a href="#pddos"><img onclick="this.src='img/pduno.png';document.getElementsByClassName('imgdp').src='img/pddos.png'" class="imgdp" src="img/pddos.png" width="13" height="11" /></a> 
<a href="#pddos"><img onclick="this.src='img/pduno.png';document.getElementsByClassName('imgdp').src='img/pddos.png'" class="imgdp" src="img/pddos.png" width="13" height="11" /></a> 

pduno.png是 「活動的」 圖像和pddos.png是 「desactive」 的形象。

讓我們像我有3個圖像pduno - pddos - pddos

當我點擊2個pddos之一,將其更改爲pduno,那就是pduno改變pddos之一。我的意思是,只有一個圖像與pduno,其餘的是pddos。

我正在使用它創建滾動畫廊。 pduno的作品展示了正在展示的畫廊。

回答

2

我會用jQuery庫那(因爲你需要使用一些不那麼簡單的功能)

可以包括它編寫這些代碼(無需下載任何東西):

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" /> 

然後,我會做到這一點:

<a href="#pddos"><img class="pdimg" src="img/pduno.png" width="13" height="11" /></a> 
<a href="#pddos"><img class="pdimg" src="img/pddos.png" width="13" height="11" /></a> 
<a href="#pddos"><img class="pdimg" src="img/pddos.png" width="13" height="11" /></a> 

在HTML,我刪除了所有的腳本,並搬到這裏他們:

<script> 
$('.pdimg').click(function(){ //This registers the function with the click event 
    $('.pdimg').attr('src', 'img/pddos.png'); //This resets the image to pddos 
    $(this).attr('src', 'img/pddos.png'); //This sets the image to uno, 
          // "this" will be the img that you clicked on. 
} 
</script> 
+0

它的工作就像我需要它。 xD非常感謝。的xD – 2012-04-16 01:34:50

1

document.getElementsByClassName將從文檔中選擇一個節點列表,而不是單個元素。要更改每個選定元素的src屬性,您必須遍歷該列表。

此外,要將所有圖像重置爲pddos,然後使其中一個活動,您不能將其中一個設置爲pduno,然後重置所有圖像。

相關問題