javascript - problem with conditions in javascript while working with DOM
问题描述
This condition is not working. When I click, it should hide all li elements and when I click again it should show all the li elements that are hidden but its not working
hide.addEventListener("click", function() {
Array.from(list.children).forEach(function(k){
if(k.style.display === "block") {
k.style.display = "none";
hide.textContent = "Show";
list.style.backgroundColor = "rgba(0, 0, 0, 33%)";
list.style.borderRadius = "8px";
document.querySelector(".hidden").style.display = "block";
input.setAttribute("disabled", "disabled");
}
else if (k.style.display === "none") {
hide.textContent = "Hide";
k.style.display = "block";
list.style.backgroundColor == "transparent";
list.style.borderRadius = "";
document.querySelector(".hidden").style.display = "none";
input.removeAttribute("disabled");
}
else {
};
})
});
解决方案
Array.from(list.children).forEach(function(k){
if(k.style.display == "block") {
k.style.display = "none";
hide.textContent = "Show";
list.style.backgroundColor = "rgba(0, 0, 0, 33%)";
list.style.borderRadius = "8px";
document.querySelector(".hidden").style.display = "block";
input.setAttribute("disabled", "disabled");
}
else if (k.style.display == "none") {
hide.textContent = "Hide";
k.style.display = "block";
list.style.backgroundColor == "transparent";
list.style.borderRadius = "";
document.querySelector(".hidden").style.display = "none";
input.removeAttribute("disabled");
}
else {
};
});
当您尝试比较两个值时,请记住使用==
or===
而不是=
. 当您使用=
它时,意味着您声明某物的价值,而当您使用时==
,===
它意味着您比较某物的两个值。===
仅在您想要真正精确时使用,例如1 == '1'
为真,而1 === '1'
为假,因为一个是整数,一个是字符串,因此它们不完全相同。
JQuery 的另一个好处是您可以使用它的许多内置函数来切换某些东西,在这种情况下,您可以使用 .toggleClass() 并具有相同的效果:
Array.from(list.children).forEach(function(k){
k.toggleClass('hidden');
});
然后在你的 CSS 中你可以有:
.hidden {
display = 'block';
}
推荐阅读
- python - 如何使用 Numpy 对字符串数组进行一次热编码?
- json - 当它们应该是值时返回为 0 的 JSON 整数
- node.js - 比较 2 个嵌入文档的特定字段后获取过滤后的文档
- r - ggplot:将x轴与不同的几何对齐(ggarrange)
- c++ - 试图在重载函数中输入字符和字符串
- c# - DrawIconEx 和 GetDIBits 的奇怪行为,alpha 为零
- r - 函数中的 lapply、glm 和 speedglm:缺少参数“数据”,没有默认值
- windows - 我在windows中安装了ros1。Rviz 未正确渲染/更新,尤其是当我尝试缩放或更改方向时。它正在显示痕迹
- r - 用数据框命名列表项?
- solr - solr 8.2 查询块连接有哪些变化?