简体   繁体   English

Javascript隐藏div和show

[英]Javascript hide div and show

I'm making a quiz and I want to hide questions when there not being asked. 我正在做测验,我想在不被问到的情况下隐藏问题。 But I keep getting the error Uncaught TypeError: Cannot read property 'style' of null. 但是我一直收到错误信息Uncaught TypeError:无法读取null的属性“样式”。

 document.getElementById("score").style.display = "none"; 
 <!--This is the questions,score and submit button --> <div id="score"> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <input type="text" name="textfield" id="textscore"> </div> </div> </div> 

Make sure the element is in the DOM when you try to hide. 尝试隐藏时,请确保该元素在DOM中。

document.onreadystatechange = () => {
  if (document.readyState === 'complete') {
    // document ready
    document.getElementById("score").style.display = "none";
  }
}

This line should be after the html element score. 此行应在html元素分数之后。

document.getElementById("score").style.display = "none";

Or put this line inside a function and call it after the html load 或者将此行放入函数中,并在html加载后调用它
Or as @arpad answered https://stackoverflow.com/a/44139647/20126 do it in the document ready. 或@arpad回答https://stackoverflow.com/a/44139647/20126时,请准备好文档。

<!doctype html>
<html>
   <head>
     <title>Solve Type Error</title>
   </head>
   <body>
     <div id="score">
       <div class="form-group">
          <div class="col-sm-offset-2 col-sm-10">   
           <input type="text" name="textfield" id="textscore">
          </div>
       </div>
     </div>

     <script>
        document.getElementById("score").style.display = "none";
     </script>
 </body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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