JavaScript catch事件

Laj*_*jos 3 javascript jquery

我有个问题.我的DOM中有太多事件.上层正在捕捉更深层次的事件.

简单示例:

<!DOCTYPE html>
<html>
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("p").click(function(){
                $(this).hide();
            })
            $("#second").click(function(){
                alert("second.");
            });
            $("#first").click(function(){
                alert("first.");
            });
        });
    </script>
    <style type="text/css">
        #first{
            width: 200px;
            height: 200px;
            background-color: red;
        }
        #second{
            width: 100px;
            height: 100px;
            background-color: green;
        }
    </style>
</head>
<body>

    <div id="first">
        <div id="second">

        </div>
    </div>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

如果有人点击第二个div,它被第一个div包围,则两个div都会捕获该事件.在这种情况下,我怎样才能捕获第二个div的click事件,并保留第一个div.

我了解了事件冒泡,而C#中的隧道问题就是这个问题.这个问题怎么称呼?如何使用JavaScript和jQuery解决问题.解决方案是否相同?

Ble*_*der 6

您只需要阻止事件传播到父元素:

$("#second").click(function (e) {
    e.stopPropagation();

    alert("second.");
});
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/EXbdt/3/