我正在寻找一些非jQuery解决方案,通过点击链接和外部addEventListener切换div。 我基本上尽了我的努力来实现它,但现在我迷了路。 有谁知道如何解决这个问题?基于点击链接切换div - 普通javascript
我的HTML代码:
<a href="#" class="switch-button" data-id="switch1">Div1</a>
<a href="#" class="switch-button" data-id="switch2">Div2</a>
<a href="#" class="switch-button" data-id="switch3">Div3</a>
<a href="#" class="switch-button" data-id="switch4">Div4</a>
<div class="switch" id="switch1" style="height: 200px; width: 200px; background: blue;"></div>
<div class="switch" id="switch2" style="height: 200px; width: 200px; background: red; display: none;"></div>
<div class="switch" id="switch3" style="height: 200px; width: 200px; background: green; display: none;"></div>
<div class="switch" id="switch4" style="height: 200px; width: 200px; background: yellow; display: none;"></div>
我基本上是想这
$('.news-toggle').click(function (e) {
var thisDataId = $(this).attr('data-id');
$('.news-toggle-box').fadeOut(300);
$('#' + thisDataId).delay(300).fadeIn(300);
e.preventDefault();
});
转换为这样的事情
window.onload = function toggleDiv(){
var buttons = document.getElementsByClassName('switch-button');
var divs = document.getElementsByClassName('switch');
for(i=0; i<buttons.length; i++){
buttons[i].addEventListener('click', function(){
for(j=0; j<divs.length; j++){
divs[j].style.display = 'none';
}
for(i=0; i<buttons.length; i++){
var dataID = buttons[i].getAttribute('data-id');
document.getElementById(dataID).style.display = 'block';
}
})
}
}
,但它不能正常工作。
非常感谢您的建议;)