gpt4 book ai didi

javascript - 选择所有其他 ID 不是 'this.id' 的元素

转载 作者:行者123 更新时间:2023-11-28 04:45:05 30 4
gpt4 key购买 nike

我有 4 个元素,在 onclick() 中只有一个 block div 会显示;

HTML:

<!--elements that will toggle block div to show-->
<p onclick="expand(this.id)" id="p1"></p>
<p onclick="expand(this.id)" id="p2"></p>
<p onclick="expand(this.id)" id="p3"></p>
<p onclick="expand(this.id)" id="p4"></p>
<!--block div-->
<div id="block_p1"></div>
<div id="block_p2"></div>
<div id="block_p3"></div>
<div id="block_p4"></div>

JS:

function expand(e) {
document.getElementById("block_" + e).style.display = "block";
document.getElementById(e).style.backgroundColor = "#425a94";
}

问题是当我点击第一个元素之后的第二个元素时,说我在 p1 之后点击 p2, block div--block_p1 在显示 block_p2 时不会消失,如何在单击第二个 block 后隐藏第一个 block ? 如果我没有使用参数我会做这样的事情:

function expand() {
document.getElementById("block_p2").style.display = "block";
document.getElementById("p2").style.backgroundColor = "#425a94";
document.getElementById("block_p1").style.display = "none";
}

我不知道如何在带有参数的情况下做同样的事情。此外,在选择第三个元素的情况下,我还需要隐藏前两个 block 。

最佳答案

首先需要隐藏所有以 id expanded_ 开头的 div,只需在其余代码之前添加这一行即可。

var allExpanded = document.querySelectorAll( "div[id^='expanded_']" );
Array.from( allExpanded ).forEach( s => (s.style.display = "none") );

你的函数变成了

function expand(e) 
{
//first hide all
var allExpanded = document.querySelectorAll( "div[id^='expanded_']" );
Array.from( allExpanded ).forEach( s => (s.style.display = "none") );
//then show specific
document.getElementById("expanded_" + e).style.display = "block";

document.getElementById(e).style.backgroundColor = "#425a94";
document.getElementById("toolbar_expand").style.display = "block";
}

关于javascript - 选择所有其他 ID 不是 'this.id' 的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49979266/

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