首页 > 解决方案 > 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 {

            };

        })
    });

标签: javascripthtmlcssdomconditional-statements

解决方案


    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';
}

推荐阅读