简体   繁体   中英

Show div hidden by “display: none” using JS?

The below HTML and JavaScript is working as expected, but I want to make sure I am using this correctly.

I have two divs but only one needs to be displayed depending on the value of mode .

HTML:

<body>
        <div id="a-div" style="display: none;">
            <button id="add" class="btnstyle">Add </button>
        </div>
        <div id="d-div" style="display: none;">
            <button id="delete" class="btnstyle">Delete</button>
        </div>
</body>

JS:

//$("#a-div").hide();
//$("#d-div").hide();

var mode = 'add';
//var mode = 'delete';
if (mode === 'add') {
    $("#a-div").show();
} else {
    $("#d-div").show();
}

This is giving me expected results. Is there a better way of reversing the style="display: none" attribute?

Your current code should be working fine, but there are many ways of solving this problem. I would recommend using jQuerys toggle() :

$("#a-div").toggle(mode === "add");
$("#a-div").toggle(mode === "delete");

Alternatively, you could give them the id´s add-div and delete-div and make one of them visible like this:

$("#" + mode + "-div").show();

You can use:

$("#a-div").toggle();

Alternatively;
.show() / .hide()
.fadeIn() / fadeOut()

You need to modify the display property of the inline style attribute.

Like this...

var mode = 'add';

if (mode === 'add') {
    $("#a-div")[0].style.display = 'block';
} else {
    $("#d-div")[0].style.display = 'block';
}

Or you can use something like inherit instead of block .

There's several methods to do this (like you can see in other answers) but i think the show() function is enough and do the work in your case.

You can also use css() method of JQuery like following :

$("#a-div").css('display','block');

Hope this helps.

Another option is to move the styles to css:

html:

    <div id="a-div" class="notdisplayed">
        <button id="add" class="btnstyle">Add </button>
    </div>
    <div id="d-div" class="notdisplayed">
        <button id="delete" class="btnstyle">Delete</button>
    </div>

css:

.notDisplayed {display:none;}

Script:

$("#a-div").addClass("notDisplayed");
$("#d-div").removeClass("notDisplayed");

This method is more general than show/hide, as it can be extended to any style rule.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM