Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

jquery show()/hide() problem in Internet Explorer?

The following html code works in Firefox, but for some reason fails in IE (Label2 is not shown). Is that a bug or I miss something?

Any help would be appreciated.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <script src="http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js" type="text/javascript">
        </script>
        <script>
            jQuery(document).ready(function(){
                function setVis(){
                    var val = $("#check").is(":checked");
                    if (val) 
                        $("#g_1").show();
                    else 
                        $("#g_1").hide();
                }

                setVis();
                $("#check").change(setVis);
            });
        </script>
    </head>
    <body>
        <span>
            <input type="checkbox" id="check" />
            <label>Label1</label>
        </span>
        <span id="g_1">
            <label>Label2</label>
        </span>
    </body>
</html>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Cause:

Per MSDN, the change event is

...fired when the contents are committed and not while the value is changing. For example, on a text box, this event is not fired while the user is typing, but rather when the user commits the change by leaving the text box that has focus.

Behavior for checkboxes is similar: in IE the event does not fire until focus is removed from the element (try it: click then tab off of the checkbox and behavior is as expected). Firefox apparently does not respect this distinction.

Solution:

Use the click event handler instead of change:

            $("#check").click(setVis);

...and behavior should be consistent across browsers.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...