简体   繁体   中英

hide and show div content via anchor

I have an anchor that's when click shows the content depending on what the id it matches. but the script doesn't work.

HTML:

<a href="javascript:ReverseDisplay('asd')">
Click to show/hide</a>

<div id="asd" style="display:none;">
<p>Content goes here.</p>
</div>

SCRIPT:

function HideContent(d) {
document.getElementById(d).style.display = "none";
}
function ShowContent(d) {
document.getElementById(d).style.display = "block";
}
function ReverseDisplay(d) {
if(document.getElementById(d).style.display == "none") { document.getElementById(d).style.display = "block"; }
else { document.getElementById(d).style.display = "none"; }
}

FIDDLE HERE

Your problem is this:

In the "Frameworks & Extensions" section, in the left sidebar of JSFiddle, you have the option " onLoad " selected. This causes your functions to be wrapped within an event listener (a function that runs only when the contents of the page has been loaded). Since your functions end up declared inside this event listener, they aren't available within the window object (the javascript's "global object"). So, when the click on the link tries to call the function, it will be " undefined " in the window object throwing an error (you can see this in the console of your browser). Just change that option to "No wrap - in head" and you will be fine. =)

In addiction, I would recommend you to name your functions with a lowered cased first letter, since it's a best practice to only start function names with a capital letter if the function is a constructor.

Remove onload from jsfiddle framework and extension 校验

Demo

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