gpt4 book ai didi

javascript - 使用通用类 javascript 显示/隐藏 div,无 Jquery

转载 作者:行者123 更新时间:2023-12-02 22:37:21 26 4
gpt4 key购买 nike

我在尝试隐藏多个具有相同类的 div 时遇到了麻烦。我希望能够单击某个单选按钮,该按钮将仅显示与该 ID 相关的数据。我试图创建一个函数来执行此操作,但无法使其正常运行。这是我一直在研究的 fiddle https://jsfiddle.net/uncj8wzf/

function hide_row(staff){
if (staff == "manager"){
if (document.getElementsByClassName("manager").style.display == "block")
{document.querySelectorAll("employee").style.display = "none"}
}
else if (staff == "employee") {
if (document.getElementsByClassName("manager").style.display == "none";)
{document.querySelectorAll("employee").style.display = "block";}
}
else if (staff == "all"){
document.querySelectorAll("manager").style.display = "block";
document.querySelectorAll("employee").style.display = "block";
}
}

<form>
<input type="radio" onclick= "hide_row('manager')">manager<br>
<input type="radio" onclick= "hide_row('employee')">employee<br>
<input type="radio" onclick= "hide_row('all')">all
</form>

<div class="manager">manger text</div>
<div class="manager">manger text</div>
<div class="manager">manger text</div>
<div class="manager">manger text</div>


<div class="employee">employee text</div>
<div class="employee">employee text</div>
<div class="employee">employee text</div>
<div class="employee">employee text</div>

最佳答案

您的代码中有一些部分对我来说毫无意义。

为什么在 hide_row 函数中使用 if 语句?具体

if (document.getElementsByClassName("manager").style.display == "block")

还有

if (document.getElementsByClassName("manager").style.display == "none";)

您肯定只想分配这些显示,而不是检查它们,对吧? (而且分号不应该在那里)

getElementsByClassName 或 querySelectorAll 的结果是数组。您需要循环遍历结果来分配显示值。

最后,不要忘记为单选按钮提供相同的 name 属性,以便它们取消选择组中的其他按钮。

这是一个可以运行的代码片段:

let managerDivs = document.getElementsByClassName("manager");
let employeeDivs = document.getElementsByClassName("employee");
let allDivs = [...managerDivs, ...employeeDivs];

function hide_row(staff) {

// reveal all the divs, then hide those that need to be hidden
for (let el of allDivs) {
el.style.display = "block";
}

if (staff == "manager") {
for (let el of employeeDivs) {
el.style.display = "none";
}
} else if (staff == "employee") {
for (let el of managerDivs) {
el.style.display = "none";
}
}
}
<form>
<input type="radio" name="showHide" onclick= "hide_row('manager')">manager<br>
<input type="radio" name="showHide" onclick= "hide_row('employee')">employee<br>
<input type="radio" name="showHide" onclick= "hide_row('all')">all
</form>

<div class="manager">manger text</div>
<div class="manager">manger text</div>
<div class="manager">manger text</div>
<div class="manager">manger text</div>


<div class="employee">employee text</div>
<div class="employee">employee text</div>
<div class="employee">employee text</div>
<div class="employee">employee text</div>

关于javascript - 使用通用类 javascript 显示/隐藏 div,无 Jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58702186/

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