显示1个div并使用Javascript单击隐藏所有其他 [英] Show 1 div and hide all others on click using Javascript
问题描述
我正在我的网站上设置个人简介"部分,我有3张员工图片和3个div,每个员工的个人简历都在下面.我想默认隐藏所有BIOS,然后仅显示与单击的图像关联的div,然后隐藏所有其他div.
I am setting up a "bio" section on my site and I have 3 images of employees and 3 divs with each of the employees bios below. I want to hide all the bios by default and then display only the div associated with the image that is clicked and hide all other divs.
当前似乎找不到元素,因为我正在获取未定义"
Currently it seems like it's not finding the elements because I am getting "undefined"
到目前为止,这是我的HTML:
Here is my HTML so far:
<div onclick="showhide('bill');" class="bio_image"><div class="name">Bill Murray</div></div>
<div onclick="showhide('bill2');" class="bio_image"><div class="name">Bill Murray</div></div>
<div onclick="showhide('bill3');" class="bio_image"><div class="name">Bill Murray</div></div>
<div class="hide" id="bill">BILL</div>
<div class="hide" id="bill2">BILL2</div>
<div class="hide" id="bill3">BILL3</div>
还有我的Javascript:
And my Javascript:
function showhide(id){
if (document.getElementById) {
var divid = document.getElementById(id);
var divs = document.getElementsByClassName("hide");
for(var div in divs) {
div.style.display = "none";
}
divid.style.display = "block";
}
return false;
}
JSFiddle
有什么想法吗?谢谢!
JSFiddle
Any ideas? Thanks!
推荐答案
使用常规的for
循环,因为for in
循环将遍历NodeList的其他属性,而不仅仅是遍历元素列表
Use a regular for
loop as a for in
loop will loop over the other properties of the NodeList and not just over the list of elements
function showhide(id){
if (document.getElementById) {
var divid = document.getElementById(id);
var divs = document.getElementsByClassName("hide");
for(var i=0;i<divs.length;i++) {
divs[i].style.display = "none";
}
divid.style.display = "block";
}
return false;
}
这篇关于显示1个div并使用Javascript单击隐藏所有其他的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!