2011-09-07 144 views
1

我試圖切換兩個圖像,但需要js處理許多不同的圖像。我如何使用ID參數進行設置?這是我走到這一步:JavaScript通過點擊圖片切換圖像

JS

function changeIt(id) 
    { 
     var theImg = document.getElementsByTagName('img')[0].src; 

     var x = theImg.split("/"); 
     var t = x.length-1; 
     var y = x[t]; 

     if(y=='red.gif') 
     { 
      document.images.boxcolor1.src='./pics/green.gif' 
     } 

      if(y=='green.gif') 
     { 
      document.images.boxcolor1.src='./pics/red.gif' 
     } 
    } 

HTML

<a href="#" onclick="changeIt('boxcolor1')"><img src='./pics/green.gif' name='boxcolor1' id='boxcolor1' border='0' /></a> 
    <a href="#" onclick="changeIt('boxcolor2')"><img src='./pics/green.gif' name='boxcolor2' id='boxcolor2' border='0' /></a> 
    <a href="#" onclick="changeIt('boxcolor3')"><img src='./pics/green.gif' name='boxcolor3' id='boxcolor3' border='0' /></a> 

正如你可以看到現在它僅適用於第一個圖像(boxcolor1)..我想它的工作通過名稱或id標籤查看所有圖片。

感謝您的幫助!

+0

爲什麼包裹在一個錨的IMG?而且JavaScript具有String對象的lastIndexOf函數。請參閱http://jsfiddle.net/LpsbP/ – amal

回答

2

嘗試:

function changeIt(id) 
{ 
    var theImg = document.getElementById(id), 
      x = theImg.src.split("/"), 
      t = x.length-1, 
      y = x[t]; 

    if(y == 'red.gif') 
    { 
     theImg.src='./pics/green.gif' 
    } 

    if(y == 'green.gif') 
    { 
     theImg.src='./pics/red.gif' 
    } 
} 

工作例如:

http://jsbin.com/ugofiz/edit

+0

我曾嘗試過,但沒有發生當我這樣做,並在JavaScript控制檯中得到一個錯誤:未捕獲TypeError:無法讀取屬性'src'爲空 – Linqan

+0

對不起,有一個問題。試試我編輯的解決方案 – binarious

+0

在JavaScript控制檯中出現同樣的錯誤.. – Linqan