我正在为 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 次调用来节省工作量。