简体   繁体   English

为什么JQuery显示/隐藏对按钮有效但对div无效?

[英]Why does JQuery show/hide work for button but not for a div?

I want to toggle the showing or hiding of a button and a div based on a condition. 我想根据条件切换按钮和div的显示或隐藏。 Currently, the JQuery hide is working for the button() but the show() is not for the div. 当前,JQuery隐藏适用于button(),但show()不适用于div。 In other words, in the javascript below, if the condition is met, the button is hidden but the div does not show. 换句话说,在下面的javascript中,如果满足条件,则按钮是隐藏的,但div不显示。

html: 的HTML:

<button type="button" id="my-button" onclick="...do something">Go</button>
<div id="my-text">Please send an email to help@mycompany.com</div>

css: CSS:

#my-text{
    display: none;
}

javascript: javascript:

<script type="text/javascript">
    (function() {
        $(document).ready(function() {
            var someConditionIsMet = //...compute something
            if (someConditionIsMet) {
                $('#my-button').hide();
                $('#my-text').show();
            }
        });
    })();
</script>

However if I change it to 但是,如果我将其更改为

            if (someConditionIsMet) {
                $('#my-button').hide();
                $('#my-text').attr("style", "display:block")
            }

then it works properly. 然后它可以正常工作。 I thought show was basically changing the display style to block so I'm not sure why I have to spell it out like this. 我以为show基本上是在改变显示样式以阻止显示,所以我不确定为什么必须这样拼写出来。 Any ideas why? 有什么想法吗?

you could simplify your code a bit to 您可以将代码简化到

$('#my-button, #my-text').toggle();

that will togle the visibility of the elements, however that probably does not solve your problem it might very well be related to how you hid the div in the first place. 这会影响元素的可见性,但是可能无法解决您的问题,这很可能与您首先隐藏div的方式有关。 Try changing that to .hide() instead of setting the css manually. 尝试将其更改为.hide(),而不是手动设置css。 There's a few ways to hide an element .show reverts just one of them (the same used for hide()) 隐藏元素有几种方法。show只还原其中一种(与hide()相同)

show works for me in this fiddle . 在这个小提琴中 show对我有用 Are you sure your conditions are being met? 您确定您的条件得到满足吗? Try throwing an alert('conditions met'); 尝试引发alert('conditions met'); inside the if to see if its being triggered. if中查看是否被触发。

Consider assigning aria-hidden attributes, then using jQuery to hide anything that you've designated as hidden to screen readers. 考虑分配aria-hidden属性,然后使用jQuery隐藏您指定为屏幕阅读器隐藏的所有内容。

Code: 码:

<button type="button" id="my-button" onclick="...do something" aria-hidden="true">Go</button>

JavaScript: JavaScript:

$('[aria-hidden="true"]').hide(); //hide anything that's marked as hidden to screen-readers

Then use .hide() and .show(), with a toggle for the aria-hidden attribute. 然后使用.hide()和.show(),以及aria-hidden属性的切换。

See a working example at http://jsfiddle.net/jhfrench/4kNPF/ 请参见http://jsfiddle.net/jhfrench/4kNPF/

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

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