How to stop event bubbling on checkbox click

2019-01-02 22:19发布

I have a checkbox that I want to perform some Ajax action on the click event, however the checkbox is also inside a container with it's own click behaviour that I don't want to run when the checkbox is clicked. This sample illustrates what I want to do:

<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>

However, I can't figure out how to stop the event bubbling without causing the default click behaviour (checkbox becoming checked/unchecked) to not run.

Both of the following stop the event bubbling but also don't change the checkbox state:

event.preventDefault();
return false;

8条回答
趁早两清
2楼-- · 2019-01-02 23:10

In angularjs this should works:

event.preventDefault(); 
event.stopPropagation();
查看更多
Luminary・发光体
3楼-- · 2019-01-02 23:12

This is an excellent example for understanding event bubbling concept. Based on the above answers, the final code will look like as mentioned below. Where the user Clicks on checkbox the event propagation to its parent element 'header' will be stopped using event.stopPropagation();.

$(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) {
              if (event.stopPropagation) {    // standard
                   event.stopPropagation();
               } else {    // IE6-8
                    event.cancelBubble = true;
               }
          });     
  });
查看更多
登录 后发表回答