gpt4 book ai didi

Javascript - 单击时设置 div 显示 - 未定义类名

转载 作者:太空宇宙 更新时间:2023-11-03 22:46:20 24 4
gpt4 key购买 nike

我正在尝试使用以下函数通过单击图像来更改是否显示 div。

function showTxt(elementClass, nr) {
"use strict";
if (document.getElementByClassName(elementClass)[nr].style.display === "none") {
document.getElementByClassName(elementClass)[nr].style.display = "block";
} else {
document.getElementByClassName(elementClass)[nr].style.display = "none";
}
}
.employees{
width: 80%;
margin-left: 10%;
}

.employee{
width: 20%;
display: inline-block;
margin-left: 5%;
vertical-align: top;
margin-right: 5%;
}

.employee_img img{
width: 100%;
}

.employee_txt{
display: none;
}
<div class="employees">

<div class="employee">
<div class="employee_img">
<img src="resources/katerina.jpg" alt="katerina">
</div>
<div class="employee_txt" id="katerina"></div>
</div>

<div class="employee">
<div class="employee_img">
<img src="resources/sindre.jpg" alt="sindre">
</div>
<div class="employee_txt" id="sindre"></div>
</div>

<div class="employee">
<div class="employee_img" onclick="showTxt(employee_txt, 2)">
<img src="resources/daniel.jpg" alt="daniel">
</div>

<div class="employee_txt" id="daniel">
<p>this is me</p>
</div>
</div>

</div>

Stack 的代码片段工具显示消息:“Uncaught ReferenceError: employee_txt is not defined”。我不知道为什么。

感谢任何帮助。

最佳答案

有几件事是错误的,它是 getElementsByClassName,元素是复数,您需要在函数调用中传递的字符串周围加上引号。

function showTxt(elementClass, nr) {
"use strict";
if (document.getElementsByClassName(elementClass)[nr].style.display === "none") {
document.getElementsByClassName(elementClass)[nr].style.display = "block";
} else {
document.getElementsByClassName(elementClass)[nr].style.display = "none";
}
}
.employees{
width: 80%;
margin-left: 10%;
}

.employee{
width: 20%;
display: inline-block;
margin-left: 5%;
vertical-align: top;
margin-right: 5%;
}

.employee_img img{
width: 100%;
}

.employee_txt{
display: none;
}
<div class="employees">

<div class="employee">
<div class="employee_img">
<img src="resources/katerina.jpg" alt="katerina">
</div>
<div class="employee_txt" id="katerina"></div>
</div>

<div class="employee">
<div class="employee_img">
<img src="resources/sindre.jpg" alt="sindre">
</div>
<div class="employee_txt" id="sindre"></div>
</div>

<div class="employee">
<div class="employee_img" onclick="showTxt('employee_txt', 2)">
<img src="resources/daniel.jpg" alt="daniel">
</div>

<div class="employee_txt" id="daniel" style="display:none;">
<p>this is me</p>
</div>
</div>

</div>

关于Javascript - 单击时设置 div 显示 - 未定义类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41768102/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com