香草javascript for循环在另一个for循环内,向所有div添加相同的类

时间:2018-07-25 11:34:35

标签: javascript for-loop

我已经看了这段JavaScript了好几个小时了,无法确定为什么每次我将鼠标悬停在rewardImg上时,都会将类开放给每个offer div。

有什么想法吗?我了解它与闭包有关,还是我需要将其放入数组中?

var offer = document.querySelectorAll(".offer");
var rewardImg = document.querySelectorAll(".rewardImg");

for(var i = 0; i < rewardImg.length; i++) {
    rewardImg[i].addEventListener("mouseover", function() {
        for(var j = 0; j < offer.length; j++) {
            offer[j].classList.add("open");
        }
    });
}

for(var i = 0; i < rewardImg.length; i++) {
    rewardImg[i].addEventListener("mouseout", function() {
        for(var j = 0; j < offer.length; j++) {
            offer[j].classList.remove("open");
        }
    });
}

2 个答案:

答案 0 :(得分:0)

基于您的original question:您需要做的是基于rewardImg进行选择。

var rewardImgs = document.querySelectorAll(".rewardImg");

for (var i = 0; i < rewardImgs.length; i++) {
  rewardImgs[i].addEventListener("mouseover", function() {
        var offer = this.parentElement.querySelector(".offer");
        offer.classList.add("open");
   });

   rewardImgs[i].addEventListener("mouseout", function() {
        var offer = this.parentElement.querySelector(".offer");
        offer.classList.remove("open");
   });

}
.rewardImg {
  width: 200px;
  height: 50px;
  background-color: red;
}

.offer {
  width: 200px;
  height: 50px;
  background-color: yellow;
}

.offer.open {
background-color: green;
}
<div>
<div class="offer">
</div>
<div class="rewardImg">
</div>
</div>

<div>
<div class="offer">
</div>
<div class="rewardImg">
</div>
</div>

<div>
<div class="offer">
</div>
<div class="rewardImg">
</div>
</div>

之所以可行,是因为在回调this中绑定了触发事件的元素(在本例中为悬停的元素),因此我们可以从那里找到其他DOM元素。

答案 1 :(得分:0)

请注意,您正在通过for循环将类添加到所有可用的offer中,因此请确保仅将其添加到必需的元素中。

Vanilla和no for循环解决方案将类似于-

document.addEventListener('mouseover', function(e) {
  if (e.target.className == 'offer') {
    var
      seq = '.rewardImg[data-seq="' + e.target.dataset.seq + '"]';
    
    var selected = document.querySelector(seq);
    selected.classList.add("open");
  }
});


document.addEventListener('mouseout', function(e) {
  if (e.target.className == 'offer') {
    var
      seq = '.rewardImg[data-seq="' + e.target.dataset.seq + '"]';
    
    var selected = document.querySelector(seq);
    selected.classList.remove("open");
  }
});
.open {
  background-color:red;
}
<div class='offer' data-seq='1'>1</div>
<div class='offer' data-seq='2'>2</div>
<div class='rewardImg' data-seq='1'>11</div>
<div class='rewardImg' data-seq='2'>22</div>

请注意,所有JavaScript都必须在on-load事件中加入