[英]Show/Hide divs depending on the result of the JavaScript object
我有 5 個隱藏的 div,只有在 object 項目為真時才能顯示。
.colors{
display: none;
}
<div class="colors" id="blue">BLUE</div>
<div class="colors" id="red">RED</div>
<div class="colors" id="green">GREEN</div>
<div class="colors" id="yellow">YELLOW</div>
var colors = { blue:false, red:false, green:true, yellow:true};
var colorsTrue = Object.keys(colors).filter((key)=> {
return colors[key] !== false;
});
過濾所有真項后,如何只顯示對應的div?
將您的過濾方法更改為此
for(let key in colors) {
if(colors[key] == true) {
document.getElementById(key).style.display = "block"
}
}
Check on JsBin https://jsbin.com/gotiqaq/edit?html,css,js,output
您可以使用DOM 選擇器根據顏色的值更改每個 div 的 css:
var colors = { blue: false, red: false, green: true, yellow: true }; Object.keys(colors).forEach(key => { document.getElementById(key).style.display = colors[key]? 'block': 'none'; });
.colors { display: none; }
<div class="colors" id="blue">BLUE</div> <div class="colors" id="red">RED</div> <div class="colors" id="green">GREEN</div> <div class="colors" id="yellow">YELLOW</div>
這將起作用:遍歷屬性並更改 id 樣式以在鍵為真時阻止。
var colors = { blue: false, red: false, green: true, yellow: true };
for (var color in colors) {
if (colors.hasOwnProperty(color)) {
if(colors[color]) {
document.querySelector(`#${color}`).style.display='block'
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.