Home > Web Front-end > JS Tutorial > body text

Prevent click events on child elements

PHPz
Release: 2018-10-10 15:35:23
forward
1528 people have browsed it

Problem description:
I encountered a strange phenomenon when debugging the page today. A click event is defined on a parent element, and below the parent element are li tags one by one. There are no click events on this. The phenomenon is that when one of the li tags is clicked, some actions will occur.

This problem has puzzled me for a long time. I went through the code several times and finally determined that when a child element is clicked, the event of the parent element will also be triggered. At that time, I attributed this phenomenon to the fact that when a click event was defined on the parent element, the click event was actually defined in this area, so when a child element was clicked, the parent element was actually clicked.

But a more scientific explanation is: if there is no click event in the child element when clicking on the child element, then the click event will automatically bubble up to the parent element until a function that can handle the click event can be found. .

The advantage of this explanation is that there is a way to block this phenomenon, that is, to prevent the bubbling of click events. For jQuery, it is stopPropagation(). For the following code, you can try it to see the difference between without stopPropagation and with stopPropagation.

The code is as follows:

<!DOCTYPE html><html><meta http-equiv="content-type" content="text/html;charset=utf8"><link rel="stylesheet" type="text/css" href=""><script src="./jQuery/jquery-2.1.4.js"></script><script type="text/javascript">
    $(function() {
        $("#mainp").click(function(event) {
            if($(this).children(&#39;ul&#39;).css("display") == "none")
                $(this).children(&#39;ul&#39;).css("display","block");            else
                $(this).children(&#39;ul&#39;).css(&#39;display&#39;,"none");
        }); 
        //阻止向上冒泡
        $("#mainp > ul").click(function(event) {
            event.stopPropagation();
        });
    });</script><title>测试如何屏蔽子元素的事件</title><body>
    <p id="mainp">
        <button>click me</button>
        <ul style="display:none">
            <li>first</li>
            <li>second</li>
            <li>third</li>
        </ul>
    </p></body></html>
Copy after login

For more related tutorials, please visit JavaScript video tutorial

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template