2009-04-11 110 views
5

我正在尋找使用JQuery而不是普通JavaScript更改多個圖像onclick,並同時更改圖像alt屬性的可訪問性。如何在點擊時更改圖片和alt屬性?

它應該是一件容易的事情,因爲我不想對變化做一些特殊的處理,但我仍然沒有找到任何有關它的事情。

這裏是我與JS做的方式(不改變alt屬性):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<title>Change Image using Javascript</title> 
<script type="text/javascript"> 
    function changeImg(image_id, image_folder){ 
    document.getElementById(image_id).src = image_folder; 
} 
</script> 
</head> 
<body> 
<div align="center"> 

<img id="image1" src="images/nameofthesubfolder/originalimage1.jpg" alt="Original Image 1" /> 
<br /> 
    <label><input type="radio" name="radio_btn1" onclick="changeImg('image1', 'images/nameofthesubfolder/image1.jpg')"/>Image 1</label> 
    <label><input type="radio" name="radio_btn1" onclick="changeImg('image1', 'images/nameofthesubfolder/image2.gif');"/>Image 2</label> 
    <label><input type="radio" name="radio_btn1" onclick="changeImg('image1', 'images/nameofthesubfolder/image3.png');"/>Image 3</label> 
    <label><input type="radio" name="radio_btn1" onclick="changeImg('image1', 'images/nameofthesubfolder/image4.jpeg');"/>Image 4</label> 
<br /> 
<br /> 
<img id="image2" src="images/nameofthesubfolder/originalimage2.jpg" alt="Original Image 2" /> 
<br /> 
    <label><input type="radio" name="radio_btn2" onclick="changeImg('image2', 'images/nameofthesubfolder/image5.gif')"/>Image 5</label> 
    <label><input type="radio" name="radio_btn2" onclick="changeImg('image2', 'images/nameofthesubfolder/image6.png);"/>Image 6</label> 
    <label><input type="radio" name="radio_btn2" onclick="changeImg('image2', 'images/nameofthesubfolder/image7.jpeg');"/>Image 7</label> 
    <label><input type="radio" name="radio_btn2" onclick="changeImg('image2', 'images/nameofthesubfolder/image8.gif');"/>Image 8</label> 
</div> 
</body> 
</html> 

,是有辦法,以避免重複的圖像/ nameofthesubfolder /?

編輯:非常感謝altCognito,但我不知道如何使用這個代碼有不同的alt屬性爲每個圖像。也許我忘了提及我正在尋找它(我的壞)。

回答

8

讓我們一起去吧。 (我通過這個最初衝)

<img id="radio_btn1" src="originalimage1.jpg" /> 
<br /> 
    <input type="radio" name="radio_btn1" value='image1.jpg' /> 
    <input type="radio" name="radio_btn1" value='image2.gif' /> 
    <input type="radio" name="radio_btn1" value='image3.png' /> 
    <input type="radio" name="radio_btn1" value='image4.jpeg' /> 

然後jQuery的:

imgFldr = 'images/nameofthesubfolder/'; 
$("input[type='radio']").click(function() { 
    $('#'+this.name).attr('src', imgFldr+this.value).attr('alt', 'newattribute'); 
}); 

See the example

你可以在這裏編輯:http://jsbin.com/esebu/edit

4

實際上,你不需要那麼多的代碼改變..

下面是一個例子:

function changeImg(image_id, image_folder) { 
    $("#" + image_id).attr({ 'src': image_folder, 'alt': image_folder }); 
} 

而且你可以保持烏爾HTML代碼..

<label><input type="radio" name="radio_btn2" onclick="changeImg('image2', 'images/nameofthesubfolder/image5.gif')"/>Image 5</label> 
+0

我也試過這個在我的網頁上它工作總是很好.. – 2011-08-25 13:26:32