I have a web page that shows an image and two arrows, with Javascript.
When the right arrow is clicked, the index increments and a new image should be loaded. When the left arrow is clicked, the index decrements and a new image should be loaded.
I added some alerts to the code which shows that the index is incremented, but the new image is still not displayed. I wo开发者_如何学Culd appreciate pointers on what's wrong with the code.
Only the initial image is always shown and it's not updated. The link change colors and the alerts are displayed.
<html>
<head>
<title> Gallery</title>
</head>
<script type="text/javascript">
var rightTarget;
var leftTarget;
var index = 516;
function rightLinkClicked(e) {
rightTarget = e.target;
rightTarget.style.color = "green";
leftTarget.style.color = "black";
index = index +1;
alert ("right1")
var img;
img=document.getElementsByTagName('img');
img.src="pics/IMG_0" + index + ".JPG";
alert ("right2 - index = IMG_0" + index + ".JPG")
}
function leftLinkClicked(e) {
leftTarget = e.target;
leftTarget.style.color = "red";
rightTarget.style.color = "black";
if (index >516) {
index = index -1;
}
var img;
img=document.getElementsByTagName('img');
img.src="pics/IMG_0" + index + ".JPG"
alert ("left - index = "+ index)
}
function addListeners() {
var rightLink = document.getElementById("rightlinkid");
rightLink.addEventListener('click', rightLinkClicked, false);
var leftLink = document.getElementById("leftlinkid");
leftLink.addEventListener('click', leftLinkClicked, false);
}
window.addEventListener('load', addListeners, false);
</script>
</head>
<body>
<a id="leftlinkid">Left Link
<img src="icons/left.gif"; alt="left arrow" title="">
</a>
<div id="myimg">
<img id="img" src="pics/IMG_0516.JPG"; alt="start arrow" title="" width="640" height="480">
</div>
<a id="rightlinkid">Right Link
<img src="icons/right.gif"; alt="right arrow" title="">
</a>
</body>
</html>
You are using getElementsByTagName
which returns a collection of DOM elements, which is not the same as your single image. You should do
img = getElementById('img');
The code img=document.getElementsByTagName('img');
returns a collection. You need to specify which images' source you want to modify, like img[index + 1].src = ...
. I think you will want to use index + 1
so that it doesn't start counting with the first image (the left arrow). A better solution might be to give all of your images the same class name and find by class (document.getElementsByClassName('myClass');
).
精彩评论