Show 1 div and hide all others on click using Javascript(使用 Javascript 显示 1 个 div 并在点击时隐藏所有其他 div)
问题描述
我在我的网站上设置了一个简历"部分,我有 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
JSFiddle
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
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;
}
JSFiddle
这篇关于使用 Javascript 显示 1 个 div 并在点击时隐藏所有其他 div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Javascript 显示 1 个 div 并在点击时隐藏所有其


基础教程推荐
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01