我正在为 div 元素开发一个简单的显示/隐藏功能,我的问题是,单击一个按钮后显示两个链接,随后单击两个显示的链接中的任何一个都会导致它们隐藏。
My script:
<script type="text/javascript">
function showHide(divId)
{
if(document.getElementById(divId).style.display === 'none')
{
document.getElementById(divId).style.display='inline';
}
else
{
document.getElementById(divId).style.display = 'none';
}
}
</script>
The affected code:
<div id="section">
<button type="button" onclick="showHide('sub1');">
<h2>Select</h2>
</button>
<div class="menu"><!-- enclosing all the menus in the menu class-->
<!--display:none makes the object disappear and taken out of the flow of the
document -->
<ul style="display:none" id="sub1" class="menu">
<!--first submenu-->
<li><a href="" onclick="showHide('ePage');">ePage</a></li>
<li><a href="" onclick="showHide('wVillage');">wVillage</a></li>
</ul>
<div style="display:none" id="ePage">
<img src="ePage.jpg" alt="Photo: ePage" />
</div>
<div style="display:none" id="wVillage">
<img src="wVillage.jpg" alt="Photo: wVillage" />
</div>
</div>
目的是按下“选择”按钮,然后将显示两个链接,单击这两个链接将显示两个图像 - 如果再次单击链接,图像应隐藏。有人可以告诉我为什么链接会隐藏起来吗?
编辑:为了将来引用,我将 a 元素的空 href 属性编辑为“#”,并将脚本编辑为:
<script type="text/javascript">
function showHide(divId)
{
node=document.getElementById(divId);
if(node.style.display==="none")
{
node.style.display="inline";
}
else
{
node.style.display="none";
}
}
</script>
*正如建议的,通过将 div 元素的 id 保存到节点而不是进行 3 次调用,这确实节省了精力。
最佳答案
代码工作正常,但是执行showHide逻辑后, <a>
的默认功能标签发生,刷新页面。为了防止这种情况,您可以将 href 属性更改为不会刷新页面的属性(例如: #
),或者您可以在点击事件上阻止Default。
演示:http://jsbin.com/eGejurO/2/edit
PS:(无关)您可以保存对要显示/隐藏的元素的引用,而不是在同一函数中查找它 3 次。
关于javascript - 显示/隐藏故障 - 有人可以指出我的错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19182253/