将JavaScript函数应用于除第i个元素外的所有数组元素

7
在我的一个项目中,我制作了3个图库,我想把它们都放在同一页上的同一位置,但不是同时显示。为了实现这个目标,我选择创建了3个按钮。例如,当我点击第一个按钮时,第一个图库应该出现(两个图库最初都是display:none),然后当我点击第二个按钮时,第二个图库应该出现,之前显示的那个应该消失,对于每个图库都是如此。我制作了一个简化版的页面,以便更容易地思考。
总的来说,我的问题是我不太知道如何将函数应用到数组中的所有元素,除了一个元素。
以下是代码:
<!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>

这可能会有所帮助:https://dev59.com/j3A75IYBdhLWcg3wlqKh - Hunan Rostomyan
1
可能是通过for循环分配事件处理程序的Javascript的重复问题。 - Andy
2个回答

2
您可以遍历所有元素,并比较按钮的索引与当前画廊项的索引:

您可以遍历所有元素,并比较按钮的index与当前画廊项的index

[].forEach.call(gallery, function (el, i) {
  el.style.display = i === index ? 'block': 'none';
});

或者:

for (var i = 0; i < gallery.length; i++) {
  gallery[i].style.display = i === index ? 'block': 'none';
}

这将循环遍历所有元素,并将每个元素的“display”设置为“none”,除了与点击按钮对应的具有“index”的元素。 示例在此
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));
}

你好,非常感谢,你的代码完美地按照我的需求工作。由于我是初学者,还有一些细节需要理解,有几个东西我还没有真正掌握。 - Chihab

1
你已经做得差不多了...遍历整个东西,当特定元素出现时,不要执行它,但我不明白这里闭包的用途是什么:
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));
  }

2
否则,每当 onclick 执行时,都需要闭包,否则 i 将始终为 button.length - 1 - Evan Trimboli
3
如果你不知道代码的作用,为什么还要写代码? - Andy
你好,感谢您的回复。我尝试了您的代码版本,但结果仍然没有改变 :( - Chihab
关于闭包,我不确定什么是正确的解释,但如果您在没有闭包的情况下尝试该代码,则for循环中使用的“i”仅适用于button-Array,而不适用于gallery-Array。因此,我认为使用闭包是将“i”赋给所涉及的所有不同数组的编程方式。 - Chihab

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接