简体   繁体   中英

How can I show a hidden text by clicking on a button?

 function myFunction() { var x = document.getElementById("myDIV"); if (x.style.display = "none") { x.style.display = "block"; } else { x.style.display = "none"; } }
 <ul> <li><button onclick="myFunction()">Try it</button> <div id="myDIV"><p>This is my DIV element.</p></div </li> </ul>

In the css file I included the command: #myDIV{ display: none; } because otherwise the text would not be hidden at first. With this code the text is hidden at first and if I click on the button it shows the text. But then if I click on the button again it should be closing the text which it does not. Can someone help me out here? Thanks!

Set this to HTML

<div id="myDIV" style="display: none;"><p>This is my DIV element.</p></div>

and this javascript

function myFunction() {
    var x = document.getElementById("myDIV");
    if (x.style.display == "none") {
        x.style.display = "block";
    } else {
       x.style.display = "none";
      }
}

This now will work because the display none isn't by default to div element so javascript will not see the display none style and will not execute the function. So you need to specify style display none and the function will work correctly

= is assignment. == and === are comparison. So inside of the if , change it to one of those two.

You also didn't properly close the <div> in the code you submitted.

Another thing is that you're setting the display: none in a CSS file. JavaScript doesn't have access to this value, it only has access to style="..." in the HTML markup of the element. To fix this issue, check if it's not hidden and swap around the sides of the if/else block.

 function myFunction() { var x = document.getElementById("myDIV"); if (x.style.display == "block") { // `=` to `==` or `===` x.style.display = "none"; } else { x.style.display = "block"; } }
 #myDIV { display: none; }
 <ul> <li><button onclick="myFunction()">Try it</button> <div id="myDIV"> <p>This is my DIV element.</p> </div> <!-- this div wasn't closed properly --> </li> </ul>

 function myFunction() { var x = document.getElementById("myDIV"); x.style.display = x.style.display != "block"?"block":"none" }
 #myDIV{ display: none; }
 <ul> <li><button onclick="myFunction()">Try it</button> <div id="myDIV"><p>This is my DIV element.</p></div </li> </ul>

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