2009-04-11 111 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