ホームページ  >  記事  >  ウェブフロントエンド  >  JavaScript がイベントのバブリングとイベント自体の発生を防ぐ方法

JavaScript がイベントのバブリングとイベント自体の発生を防ぐ方法

autoload
autoloadオリジナル
2021-04-09 11:27:181965ブラウズ

Javascript では、イベント バブリングはノードによって生成され、親ノードに影響を与え、段階的に上昇し、最終的にページ全体にゆっくりと影響を及ぼしますが、場合によってはイベント バブリングが発生しないようにしたい場合があります。 . それともイベント自体の発生でしょうか?この記事では一緒に調べていきます。

1. イベントの発生を防ぐ

<!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. イベントの発生を防ぐ

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

推奨: 「2021 js 面接の質問と回答 (大要約)

以上がJavaScript がイベントのバブリングとイベント自体の発生を防ぐ方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。