【问题标题】:show/hide malfunction - could someone point out my error?显示/隐藏故障 - 有人可以指出我的错误吗?
【发布时间】:2013-10-04 13:19:22
【问题描述】:

我正在为 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 次调用,这确实节省了工作量。

【问题讨论】:

  • 该代码对我来说似乎工作正常。可能您的锚 (a) 标签在点击时重定向。
  • 尝试在a标签的onclick属性中添加return false;showHide(...)之后。

标签: javascript function xhtml


【解决方案1】:

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

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

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

【讨论】:

  • 感谢所有伟大的 cmets!这是我的第一篇文章 - 特别感谢 Tibos 提供的 jsbin 示例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-15
相关资源
最近更新 更多