三个js循环在一个

时间:2017-08-04 11:22:21

标签: javascript loops

嘿,我只想做一个循环,它有三个按钮和三个下拉列表。但我必须创建三个列表,因为当我连接它们时,connect也会下拉列表。我的三个循环看起来像:

var arrow = document.getElementsByClassName('list_arrow');
var list = document.getElementsByClassName('list_panel');

for (var i = 0; i < arrow.length; i++) {
   arrow[0].addEventListener('click', function() {
      for (var i = 0; i < list.length; i++) {
         list[0].classList.toggle('list_panel_open');
      }
   });
}

for (var i = 0; i < arrow.length; i++) {
   arrow[2].addEventListener('click', function() {
      for (var i = 0; i < list.length; i++) {
         list[2].classList.toggle('list_panel_open');
      }
   });
}

for (var i = 0; i < arrow.length; i++) {
   arrow[1].addEventListener('click', function() {
      for (var i = 0; i < list.length; i++) {
         list[1].classList.toggle('list_panel_open');
      }
   });
}

我怎么能在一个循环中写这个呢?

2 个答案:

答案 0 :(得分:0)

You don't need the loop within the loops either:

for (var i = 0; i < arrow.length; i++) {
   arrow[i].addEventListener('click', function() {
      list[i].classList.toggle('list_panel_open'); 
      // since all of the `i` numbers are the same
   });
}

答案 1 :(得分:0)

You should not combine 2 sets of queried elements like that. You are not guaranteed that the index in the array is the same everywhere. Instead set a attribute on the button(data-id). In the onClickElement handler I get the data-id and use it to toggle the target element.

var q = document.querySelectorAll.bind(document);

function toggleElement(id){
  q("#" + id)[0].classList.toggle('hidden');
}

function onClickElement(){
  var toggleId = this.getAttribute('data-id');
  toggleElement(toggleId);
}

q('.arrow').forEach(function(element){
  element.addEventListener('click', onClickElement);
});
.hidden{
  display: none;
}
<button class="arrow" data-id="p1">1</button>
<button class="arrow" data-id="p2">2</button>
<button class="arrow" data-id="p3">3</button>
<br>
<br>
<div id="p1" class="panel hidden">Panel 1</div>
<div id="p2" class="panel hidden">Panel 2</div>
<div id="p3" class="panel hidden">Panel 3</div>