Apply a JavaScript function to all Array elements except the ith element
In one of my projects I made 3 galleries, I would like to put both of them on the same page in the same position, not at the same time, however. For this to be possible, I chose to create 3 buttons. When I click on the first button for example, the first gallery should appear (both galleries are initially on display:none), then when I click on the second button, the second one should appear and the one shown before should disappear, and so for each of the galleries. I made a simplified copy of the page to make the thinking easier.
In general, my problem is that I don't quite know how to apply a function to all the elements in an Array except for one element.
Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Galleries</title>
<link rel="stylesheet" type="text/css" href="gs.css">
<style type="text/css">
body{
background-color:royalblue;
}
header{
text-align: center;
}
article{
width:95%;
margin:auto 2.5% auto 2.5%;
height:850px;
background-color:tomato;
display:none;
}
</style>
</head>
<body>
<header>
<button>Third Gallery</button>
<button>Second Gallery</button>
<button>Third Gallery</button>
</header>
<section>
<article>
<h1>This is the first gallery</h1>
</article>
<article>
<h1>This is the second gallery</h1>
</article>
<article>
<h1>This is the third gallery</h1>
</article>
</section>
<script type="text/javascript">
var button=document.getElementsByTagName('button');
var gallery=document.getElementsByTagName('article');
for(var i=0; i<button.length; i++){
(function(index){
button[index].onclick=function(){
gallery[index].style.display="block";
}
}(i));
}
</script>
</body>
</html>
你所做的几乎是正确的......循环遍历整个事物,当特定元素出现时,不要这样做,但我不明白这里使用闭包的含义是什么:
var button=document.getElementsByTagName('button');
var gallery=document.getElementsByTagName('article');
for(var i=0; i<button.length; i++){
if (i != 2) // Make sure `i` is not equal to 2.
(function(index){
button[index].onclick=function(){
gallery[index].style.display="block";
}
}(i));
}
You could iterate over all the elements and compare the index
of the button with the index
of the current gallery item:
[].forEach.call(gallery, function (el, i) {
el.style.display = i === index ? 'block': 'none';
});
or:
for (var i = 0; i < gallery.length; i++) {
gallery[i].style.display = i === index ? 'block': 'none';
}
This will loop over all the elements and set the display
of each element to none
except for the on with an index
that corresponds to the clicked button.
Example Here
var button = document.getElementsByTagName('button');
var gallery = document.getElementsByTagName('article');
for (var i = 0; i < button.length; i++) {
(function(index) {
button[index].onclick = function() {
[].forEach.call(gallery, function (el, i) {
el.style.display = i === index ? 'block': 'none';
});
}
}(i));
}
链接地址: http://www.djcxy.com/p/89186.html