问题
I really need some help, I wanna know what's the best way to hide and show elements by clicking on a link just using Java Script without Jquery.
So, when I click on the "Link 1" need to add the "class active" and just the "<div id="cont1">
" should be shown while the others should be hidden.
Other thing, is do this with the possibility to add more HTML Links and Content in the future, without the necessity to change the JS code.
I will be eternally grateful if someone help me!
Follow the HTML code:
<div class="all">
<ul class="links">
<li class="active"><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
<li><a href="#">Link 3</a></li>
<li><a href="#">Link 4</a></li>
</ul>
<div class="content">
<div id="cont1">
<p>Content 1</p>
</div>
<div id="cont2">
<p>Content 2</p>
</div>
<div id="cont3">
<p>Content 3</p>
</div>
<div id="cont4">
<p>Content 4</p>
</div>
</div>
</div>
回答1:
Just try to fix your code.
- add missing
[0]
afterdocument.getElementsByClassName("content")
- change
getElementsByClassName()
toquerySelectorAll()
in order to work in IE8 - change variable
i
innavList.children[i].onclick
to remembered variableindex
- change variable
i
start value to0
- pass
index + 1
as a dest ofmudaConteudo()
since index start with 0 but your content ids start with 1
Here the result:
window.onload = function () {
function mudaConteudo(elm, dest) {
var divs = document.querySelectorAll(".content")[0].getElementsByTagName('div');
for (var i = 0, len = divs.length; i < len; i++) {
divs[i].style.display = "none";
}
document.getElementById('cont' + dest).style.display = "block";
}
var navList = document.querySelectorAll(".links")[0];
for (var i = 0, len = navList.children.length; i < len; i++) {
(function(index){
navList.children[index].onclick = function () {
mudaConteudo(this, index + 1);
document.querySelectorAll(".active")[0].removeAttribute("class");
this.className = "active";
};
})(i);
}
}
Hope this help.
回答2:
Try this:
var list = document.getElementsByTagName('ul');
var links = list[0].getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
links[i].onclick = function () {
var target = this.innerHTML.substr(-1);
var divs = document.getElementsByClassName("content");
var subdivs = divs[0].getElementsByTagName('div');
for (var i = 0; i < subdivs.length; i++) subdivs[i].style.display = 'none';
document.getElementById('cont' + target).style.display = 'block';
};
};
jsFiddle example
来源:https://stackoverflow.com/questions/15884640/hide-and-show-elements-by-clicking-on-a-link-with-java-script-without-jquery