ppl*_*iti 1 html javascript dom
我有4个元素,onclick()只有一个blockdiv会显示;
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>
Run Code Online (Sandbox Code Playgroud)
JS:
function expand(e) {
document.getElementById("block_" + e).style.display = "block";
document.getElementById(e).style.backgroundColor = "#425a94";
}
Run Code Online (Sandbox Code Playgroud)
问题是当我点击第一个元素之后的第二个元素时,我说点击p2之后p1,块div-- block_p1不会block_p2如图所示消失,如何在点击第二个块之后隐藏第一个块?如果我没有使用参数,我会做这样的事情:
function expand() {
document.getElementById("block_p2").style.display = "block";
document.getElementById("p2").style.backgroundColor = "#425a94";
document.getElementById("block_p1").style.display = "none";
}
Run Code Online (Sandbox Code Playgroud)
我不知道在带参数的情况下如何做同样的事情.同样在选择第三个元素的情况下,我也需要隐藏前两个块.
您首先需要隐藏所有以id开头的div expanded_,只需在其余代码之前添加此行.
var allExpanded = document.querySelectorAll( "div[id^='expanded_']" );
Array.from( allExpanded ).forEach( s => (s.style.display = "none") );
Run Code Online (Sandbox Code Playgroud)
你的功能变得
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";
}
Run Code Online (Sandbox Code Playgroud)