我正在努力使用下面的代码,当点击带有类testButton的div时,它会缩进以使用类testContent隐藏div。 在我的代码中,看起来addEventlistener只是“记住”循环的最后一个元素。
<div>
<div class="test testContent">
Test Content 1
</div>
<div class="test testButton">Test</div>
<div class="test testContent">
Test Content 2
</div>
<div class="test testButton">Test</div>
<div class="test testContent">
Test Content 3
</div>
<div class="test testButton">Test</div>
<div class="test testContent">
Test Content 4
</div>
<div class="test testButton">Test</div>
</div>
<script type="text/javascript">
// Get elements with the class test
var divArray = document.getElementsByTagName('div');
// Check if given element has the class
function elementHasClass(element, classMatch) {
return (' ' + element.className + ' ').indexOf(' ' + classMatch + ' ') > -1 ? true : false;
}
// Get element by classname
function getElementWithClass(elementArray, classMatch) {
// Store matches
var matches = [];
for (i in elementArray) {
if (elementHasClass(elementArray[i], classMatch)) {
matches.push(elementArray[i]);
}
}
return matches;
}
var testArray = getElementWithClass(divArray, 'test');
// Hide previous text div on click
for (var i = 0; i < testArray.length; i++) {
if(elementHasClass(testArray[i], 'testButton')) {
// Add event listener if previous content element exists
if (elementHasClass(testArray[i - 1], 'testContent')) {
testArray[i].addEventListener('click', function() {
// Hide previous content element
testArray[i - 1].style.display = 'none';
}, false);
}
}
}
</script>