如何在复选框点击停止事件冒泡 [英] How to stop event bubbling on checkbox click

查看:87
本文介绍了如何在复选框点击停止事件冒泡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;


推荐答案

替换

event.preventDefault();
return false;

event.stopPropagation();

event.stopPropagation() p>

event.stopPropagation()


停止一个事件的冒泡到
父元素,防止任何父
处理程序被通知
事件。

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

event.preventDefault() b
$ b

event.preventDefault()


阻止浏览器执行
默认操作。使用
isDefaultPrevented方法知道是否曾经调用过此方法
(在
事件对象上)。

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

这篇关于如何在复选框点击停止事件冒泡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆