1

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

4

1 回答 1

1

代码正常工作,但在执行 showHide 逻辑后,<a>标签的默认功能发生,刷新页面。为了防止它发生,您可以将 href 属性更改为不会刷新页面的内容(例如#:),或者您可以在 click 事件上使用 preventDefault 。

演示:http: //jsbin.com/eGejurO/2/edit

PS:(无关)您可以保存对您正在显示/隐藏的元素的引用,而不是在同一函数中查找它 3 次。

于 2013-10-04T13:28:12.523 回答