我可以将for循环重用于多个功能吗?

时间:2019-05-24 11:42:31

标签: javascript

我想重用一个for循环,该循环遍历我已命名为'allRooms'的querySelectorAll变量,但我不确定该如何做。我希望能够在循环中的元素上添加/删除类。在下面的代码中,我两次使用了相同的for循环,尽管它执行不同的事情,但仍在相同的“ allRooms”变量上循环,这是我要避免的操作。感谢您的帮助,我仍在学习javascript。 这是即时通讯使用javascript的效果 https://iamrufus.github.io/

(function() {
  let roomsWrap = document.querySelector('.rooms__wrap');
  let roomImg = document.querySelectorAll('.rooms__img');
  let allRooms = document.querySelectorAll('.rooms__type');
  let roomType;

  roomsWrap.addEventListener('mouseover', function(e) {
    reset();
    if (e.target.classList.contains('rooms__type')) {
      roomType = e.target.dataset.room;
      roomImg[roomType].classList.add('active');
      e.target.classList.add('active');
    }
    for (var i = 0; i < allRooms.length; i++) {
      allRooms[i].classList.add('hide');
      e.target.classList.remove('hide');
    }
  });

  roomsWrap.addEventListener('mouseleave', function() {
    reset();
  });

  function reset() {
    for (var i = 0; i < allRooms.length; i++) {
      allRooms[i].classList.remove('active', 'hide');
    }
    for (var i = 0; i < roomImg.length; i++) {
      roomImg[i].classList.remove('active');
    }
  }
})();
<section class="section rooms">
  <div class="rooms__wrap">
    <div class="rooms__img__wrap">
      <div class="rooms__img rooms__img--traditional"></div>
      <div class="rooms__img rooms__img--grande"></div>
      <div class="rooms__img rooms__img--deluxe"></div>
    </div>
    <div class="rooms__type__wrap">
      <div class="rooms__type rooms__type--traditional" data-room="0"></div>
      <span class="rooms__type__name">Traditional Suite</span>
    </div>
    <div class="rooms__type__wrap">
      <div class="rooms__type rooms__type--grande" data-room="1"></div>
      <span class="rooms__type__name">Grande Suite</span>
    </div>
    <div class="rooms__type__wrap">
      <div class="rooms__type rooms__type--deluxe" data-room="2"></div>
      <span class="rooms__type__name">Deluxe Suite</span>
    </div>
  </div>
</section>

1 个答案:

答案 0 :(得分:0)

我不推荐这样做,但是您可以将for循环包装在参数驱动的函数中,该函数根据该参数执行不同的操作。

类似的东西:

function doAllRooms(param, e) {

  for (var i = 0; i < allRooms.length; i++) {
    if (param == 1) {
      allRooms[i].classList.add('hide');
      e.target.classList.remove('hide');
    }
    if (param == 2) {
      allRooms[i].classList.remove('active', 'hide');
    }
  }
}


roomsWrap.addEventListener('mouseover', function(e) {
  doAllRooms(1, e);
});

function reset() {
  doAllRooms(2);
}