Home >Web Front-end >JS Tutorial >How Javascript prevents events from bubbling and the event itself from occurring

How Javascript prevents events from bubbling and the event itself from occurring

autoload
autoloadOriginal
2021-04-09 11:27:182061browse

In Javascript, event bubbling is generated by the node, and then affects the parent node, rising step by step, and finally slowly affecting the entire page, but sometimes we want to prevent event bubbling from happening. Or even the occurrence of the event itself? This article will take you to find out together.

1. Prevent events from bubbling up

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .boxA {
            overflow: hidden;
            width: 300px;
            height: 300px;
            margin: 100px auto;
            background-color: blue;
            text-align: center;
        }       
        .boxB {
            width: 200px;
            height: 200px;
            margin: 50px;
            background-color: green;
            line-height: 200px;
            color: #fff;
        }
    </style>
</head>

<body>
    <div class="boxA">
        <div class="boxB">boxB</div>
    </div>
    <script>
        var boxA = document.querySelector(&#39;.boxA&#39;);
        var boxB = document.querySelector(&#39;.boxB&#39;);
        boxA.onclick = function (e) {
        console.log(&#39;我被点击了boxA&#39;);
    };
    boxB.onclick = function (e) {
        e.cancelBubble=true; //不冒泡
        console.log(&#39;我被点击了boxB&#39;);
    };
    </script>
</body>
</html>

2. Prevent events from occurring

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<form action="http://www.php.cn" method="POST">
<button type="submit">按钮1</button>
</form>    
<body>
    <script>
        const btn=document.querySelector("button");
        console.log(btn);
        btn.addEventListener("click",function(e){
            e.preventDefault();
        });
    </script>
</body>
</html>

Recommended: "2021 js interview questions and answers (large summary)"

The above is the detailed content of How Javascript prevents events from bubbling and the event itself from occurring. For more information, please follow other related articles on the PHP Chinese website!

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