JavaScript error event

I have a problem. I have too many events in the DOM. The upper level captures a deeper event.

Simple example:

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

      

If someone clicks on the second div that is wrapped in the first div, both of them will capture the event. In this situation, how can I only catch the second div click event and leave the first div.

I found out about event bubbles and tunneling in C # is a problem. What is this problem called? How can I solve the problem with JavaScript and jQuery. Is the solution the same?

+3


source to share


1 answer


You just need to stop the event from propagating to the parent elements:

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

    alert("second.");
});

      



Demo: http://jsfiddle.net/EXbdt/3/

+6


source







All Articles