当我点击下一个按钮时,我需要通过迭代或纯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;
答案 0 :(得分:1)
因此,请使用node.nextSibling
或node.nextElementSibling在单击的元素后引用该元素。
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;