单击使用JavaScript获取每个循环的下一次迭代

时间:2017-09-13 12:48:39

标签: javascript

当我点击下一个按钮时,我需要通过迭代或纯JavaScript中的data-id为每个循环获取下一个div。



var stepsWrp = document.querySelectorAll('.stepWrp');

stepsWrp.forEach(function(item, index){

	item.addEventListener('click', function (event) {
		if (event.target.nodeName === 'BUTTON' && 
			event.target.innerText === 'Next' &&
			event.target.classList.contains('nextBtn')
			) {				


			      
		}
})
})

.stepWrp {
display:inline-block;
width:100px;
height:100px;
border:1px solid #ccc;
}
.active {
border:1px solid red;
}

<div class="stepWrp" data-id="1">
    text content 1  
    <button class="nextBtn">Next</button>
</div>
<div class="stepWrp" data-id="2">
    text content 2   
    <button class="nextBtn">Next</button>
</div>
<div class="stepWrp" data-id="3">
    text content 3 
    
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

因此,请使用node.nextSiblingnode.nextElementSibling在单击的元素后引用该元素。

&#13;
&#13;
var stepsWrp = document.querySelectorAll('.stepWrp');
stepsWrp.forEach(function(item, index) {
  item.addEventListener('click', function(event) {
    console.log(item.nextElementSibling)
  })
})
&#13;
.stepWrp {
  display: inline-block;
  width: 100px;
  height: 100px;
  border: 1px solid #ccc;
}

.active {
  border: 1px solid red;
}
&#13;
<div class="stepWrp" data-id="1">
  text content 1
  <button class="nextBtn">Next</button>
</div>
<div class="stepWrp" data-id="2">
  text content 2
  <button class="nextBtn">Next</button>
</div>
<div class="stepWrp" data-id="3">
  text content 3

</div>
&#13;
&#13;
&#13;