如何使用循环使用Java脚本更改div ID

时间:2018-10-02 11:59:12

标签: javascript html

我正在执行使用简单的Vanilla Javascript更改HTML内容的任务。

已经给出了HTML,我只需要编写JS部分的代码即可。

任务包括根据单击的按钮更改HTML内容。如果单击“红色”,则只应显示红色说明,其他颜色也应相同。

HTML,CSS和JS代码包括:

function show_meaning(color){
  document.getElementById("empty_div").style.display = "none";
  document.getElementById("body").style.backgroundColor = color;
  document.getElementById(color).style.display = "block";

  if(color=="red"){
      document.getElementById("blue").style.display = "none";
      document.getElementById("green").style.display = "none"
  } else if(color=="blue"){
      document.getElementById("red").style.display = "none";
      document.getElementById("green").style.display = "none";

  } else{
      document.getElementById("blue").style.display = "none";
      document.getElementById("red").style.display = "none"
  } 
}
#red, #blue, #green{
  display:none;
}

#empty_div{
  display:block;
}
<div id="empty_div">
  <h3> Click on the button below to see the meaning of each colour!</h3>
</div>

<div id="red">
  Red is the color of fire and blood, so it is associated with energy, war, 
    danger, strength, power, determination as well as passion, desire, and love. 
</div>
<div id="green">Green is the color of growth and health. </div> 
<div id= "blue">Blue is the color of the sky and sea. </div>
</div>
<button onclick="show_meaning('red')">RED</button>        
<button onclick="show_meaning('green')">GREEN</button>
<button onclick="show_meaning('blue')">BLUE</button>
</div>

我的问题是,如何使用for或while循环获得相同的结果?

1 个答案:

答案 0 :(得分:1)

首先,您可以创建一个功能来重置(隐藏)所有div,然后应用该功能以显示所需的div。您将不需要for循环,因为如果这样做,则必须将所有id添加到数组中,以防您想添加新项目。 这是解决您问题的简单方法:

const show_meaning = (color) => { 
  hideAll();
  let color_div = document.getElementById(color);
  color_div.style.backgroundColor = color;
  color_div.style.display = 'block';
}

const hideAll = () => {
  
  const items = document.querySelectorAll('.color-item');
  items.forEach( (item) => item.style.display = 'none' );
  
}
//hideAll();
/**#red, #blue, #green {
  display:none;
}
no longer need this
**/
#empty_div{
  display:block;
}
.color-item { 
 display: none;
}
<div id="empty_div">
  <h3> Click on the button below to see the meaning of each colour!</h3>
</div>

<div id="red" class="color-item">
  Red is the color of fire and blood, so it is associated with energy, war, 
    danger, strength, power, determination as well as passion, desire, and love. 
</div>
<div id="green" class="color-item">Green is the color of growth and health. </div> 
<div id= "blue" class="color-item">Blue is the color of the sky and sea. </div>

<button onclick="show_meaning('red')">RED</button>        
<button onclick="show_meaning('green')">GREEN</button>
<button onclick="show_meaning('blue')">BLUE</button>

另外,请确保您修复了HTML,并且上面还有额外的div标记。