简体   繁体   English

通过锚隐藏和显示div内容

[英]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. 我有一个锚点,即单击时根据其匹配的ID显示内容。 but the script doesn't work. 但该脚本不起作用。

HTML: 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. “框架和扩展”部分的JSFiddle左侧栏中,选择了“ onLoad ”选项。 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"). 由于您的函数最终在此事件侦听器中声明,因此它们在window对象(javascript的“全局对象”)中不可用。 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. 只需将该选项更改为“ No wrap-in head” ,就可以了。 =) =)

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 从jsfiddle framework and extension删除onload 校验

Demo 演示版

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

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