简体   繁体   中英

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. Currently, the JQuery hide is working for the button() but the show() is not for the div. In other words, in the javascript below, if the condition is met, the button is hidden but the div does not show.

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:

#my-text{
    display: none;
}

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. 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. Try changing that to .hide() instead of setting the css manually. There's a few ways to hide an element .show reverts just one of them (the same used for hide())

show works for me in this fiddle . Are you sure your conditions are being met? Try throwing an alert('conditions met'); inside the if to see if its being triggered.

Consider assigning aria-hidden attributes, then using jQuery to hide anything that you've designated as hidden to screen readers.

Code:

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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