简体   繁体   English

用户需要两次单击才能删除具有javascript切换可见性的div块

[英]It is taking the user two clicks to remove a div block with javascript toggle visibility

I am using the following code and it works, somewhat, but in production it requires user to click the link twice. 我正在使用以下代码,虽然有些起作用,但是在生产中,它要求用户单击链接两次。 very weird. 很奇怪。

Is my code out of date or something? 我的代码过期了吗? any time you can offer would be appreciated. 任何时候您都可以提供将不胜感激。

js: js:

    function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
    }

html: HTML:

                    <div id="top_min_order_alert">
                        <p>Minimum Order: $5 for carry out orders, $10 for delivery (before tax and delivery fee)</p>
                        <p>Online ordering stops 15 minutes before closing time</p>
                        <p><a href="#" onclick="toggle_visibility('top_min_order_alert');">Ok, Got it.</a></p>
                    </div>

The first time the user clicks the link, e.style.display is equal to an empty string, so the if takes the else branch and e.style.display is set to block , for this reason the div remains visible. 用户第一次单击链接时, e.style.display等于一个空字符串,因此if接受else分支,并且e.style.display设置为block ,因此div仍然可见。 Then, when the user clicks the second time, e.style.display is equal to block and it is set correctly to none . 然后,当用户第二次单击时, e.style.display等于block并且正确设置为none To fix it, check if e.style.display is equal to an empty string: 要解决此问题,请检查e.style.display是否等于空字符串:

if (e.style.display === '' || e.style.display == 'block')

Here the complete example: 这里是完整的示例:

 function toggle_visibility(id) { var e = document.getElementById(id); if (e.style.display === '' || e.style.display == 'block') e.style.display = 'none'; else e.style.display = 'block'; } 
 <div id="top_min_order_alert"> <p>Minimum Order: $5 for carry out orders, $10 for delivery (before tax and delivery fee)</p> <p>Online ordering stops 15 minutes before closing time</p> <p><a href="#" onclick="toggle_visibility('top_min_order_alert');">Ok, Got it.</a> </p> </div> 

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

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