简体   繁体   中英

Stuck with onclick and document.GetElementById

I just began JavaScript and I've been stuck for a few hours now with an onclick which is not working, or maybe it's the document.getElementById . What I want to do is hide the div when I click on it.

If anyone can explain me what I'm doing wrong I would be grateful!

 function closing() { var closecook = document.getElementById("cookies"); closecook.style.display = "none"; } 
 #cookies{ display: block; } 
 <div id="cookies" onclick="closing()"> Our website is using cookies, click here to close this message. </div> 

Here's my relevant HTML markup:

<body>
<div id="cookies" onclick="closing()">
    Our website is using cookies, click here to close this message.
</div>
</body>
<script type="text/javascript" src="functions.js"></script>

Thanks.

  1. Place your "script" block at the end of your body, not outside of it!
  2. alter you the function "closing" to something like this:

    function closing() { var closecook = document.getElementById("cookies"); console.log(closecook); closecook.style.display = "none"; }

  3. In your browser: open the console by hitting "F12" or right-click anywhere in your browser and select "inspect element" then choose "console".

  4. Now execute your function by clicking on the div.

If you see a "null" in the console: the problem comes from "document.getElementById("");".

If you do not see anything pop up in the console, your javascript file is not loaded properly. Make sure there is no typo in the file name! (Linux is case-sensitiv!).

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