2012-04-16 28 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,然后重置所有图像。