问题

我有一个复选框,我想对点击事件执行一些Ajax操作,但是复选框也在一个容器内,它有自己的点击行为,当我点击复选框时,我不想运行.此示例说明了我要做什么:

<html lang="en">
    <head>
        <title>Test</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
        <script type="text/javascript">
        $(document).ready(function() {
            $('#container').addClass('hidden');
            $('#header').click(function() {
                if($('#container').hasClass('hidden')) {
                    $('#container').removeClass('hidden');
                } else {
                    $('#container').addClass('hidden');
                }
            });
            $('#header input[type=checkbox]').click(function(event) {
                // Do something
            });
        });
        </script>
        <style type="text/css">
        #container.hidden #body {
            display:none;
        }
        </style>
    </head>
    <body>
        <div id="container">
            <div id="header">
                <h1>Title</h1>
                <input type="checkbox" name="test" />
            </div>
            <div id="body">
                <p>Some content</p>
            </div>
        </div>
    </body>
</html>

但是,我不知道如何停止事件冒泡,而不会导致默认点击行为(复选框变为选中/未选中)不运行.

以下两个操作都会停止事件冒泡,但不会更改复选框状态:

event.preventDefault();
return false;


解决方法

更换

event.preventDefault();
return false;

event.stopPropagation();

event.stopPropagation()

Stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event.

event.preventDefault()

Prevents the browser from executing the default action. Use the method isDefaultPrevented to know whether this method was ever called (on that event object).




相关问题推荐