问题描述
我在我的网站上设置了一个简历"部分,我有 3 张员工图片和 3 个 div,下面是每个员工的简历.我想默认隐藏所有的bios,然后只显示与单击的图像关联的div,并隐藏所有其他div.
目前它似乎没有找到元素,因为我得到未定义"
到目前为止,这是我的 HTML:
还有我的 Javascript:
function showhide(id){如果(document.getElementById){var divid = document.getElementById(id);var divs = document.getElementsByClassName("hide");for(div中的var div){div.style.display = "无";}divid.style.display = "块";}返回假;}
JSFiddle
有什么想法吗?谢谢!
解决方案
使用常规的
for
循环,因为 for in
循环将遍历 NodeList 的其他属性而不仅仅是元素列表
function showhide(id){如果(document.getElementById){var divid = document.getElementById(id);var divs = document.getElementsByClassName("hide");for(var i=0;i
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"
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>
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!
解决方案
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;
}
这篇关于使用 Javascript 显示 1 个 div 并在点击时隐藏所有其他 div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!