gpt4 book ai didi

javascript - 如何使用循环使用 Javascript 更改 div id

转载 作者:行者123 更新时间:2023-11-30 20:08:49 25 4
gpt4 key购买 nike

我的任务是使用简单的 Vanilla Javascript 更改 HTML 内容。

HTML 已经给了,我只需要编写 JS 部分。

任务包括根据单击的按钮更改 HTML 内容。如果点击“RED”,则只出现红色解释,其他颜色也一样。

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 循环获得相同的结果?

最佳答案

首先您可以创建一个函数来重置(隐藏)所有 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 标签。

关于javascript - 如何使用循环使用 Javascript 更改 div id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52607883/

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