The following code is to achieve a function similar to an album. In order to speed up the loading of only the small picture, when the user clicks on the small picture, the corresponding large picture will be displayed in the box below. The original large image is a blank image.
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
</head>
<body>
<h2>Beauty gallery</h2>
<div id="imagegallery">
<a href="images/1.jpg" title=A "beauty" >
<img src="images/1-small.jpg" alt="The beauty 1">
</a>
<a href="images/2.jpg" title="The beauty B">
<img src="images/2-small.jpg" alt="The beauty of 2">
</a>
<a href="images/3.jpg" title="The beauty C" >
<img src="images/3-small.jpg"alt="Three beauties">
</a>
<a href="images/4.jpg" title="The beauty D" >
<img src="images/4-small.jpg" alt="The beauty 4">
</a>
</div>
<! -- Clear float -->
<div style="clear:both"></div>
<! -- Show a blank picture first -->
<img id="image" src="images/placeholder.png" alt="" width="450px">
<p id="des">Select an image</p>
<script>
// Get the element
var imagegallery = document.getElementById("imagegallery");
var links = imagegallery.getElementsByTagName("a");
var image = document.getElementById("image");
var des = document.getElementById("des");
// Go through the number group, add click time
for(var i=0; i<=links.length-1; i++){
links[i].onclick = function(){
// Change the SRC of the image
image.src = links[i].href;
// Change the text content inside des a
des.innerText = links[i].title;
// unjump element A
return false;
};
}
</script>
</body>
</html>
Copy the code
In the code above, each tag is bound to a single machine time, which looks fine, but in the page we find:
- When clicking on the smaller image, the image does not appear in the larger image we want to appear, for elimination
<a>
Label jumpreturn false
The statement also does not take effect, but opens directly<a>
The SRC path in the tag (e.gimages/1.jpg
).
This is because all the batch-added events are already successful when the binding events added inside the for loop are fired, after the loop ends. If there is a variable I inside the event function of the batch-bound event, note that the function is executed after the loop ends.
The variable defined inside the loop is a global variable, and the value of the I variable executed after the loop is the value of I when it breaks out of the loop.
So links[I] does not select the tag of the binding. Instead, we should use this, which refers to the event source before onclicke. Links [I]
for(var i=0; i<=links.length-1; i++){
links[i].onclick = function(){
// Change the SRC of the image
image.src = this.href;
// Change the text content inside des a
des.innerText = this.title;
// unjump element A
return false;
};
}
Copy the code
This correctly changes the SRC of the following large image to href in the current tag.