jquery closestメソッドを使って指定した要素以外のクリックイベントを判別する

jqueryでclosestメソッドを使うと「指定した要素以外のクリックイベント」を判別することができます。ここでは、closestメソッドを実際に使用して、ボタンのクリックを判別するサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
※windows10にApacheのインストールはこちら
closest使い方
ボタンA がクリックされたか、それ以外の画面がクリックされたかを判別するサンプルコードとなります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>mebeeサンプル</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons"> <link rel="stylesheet" href="https://unpkg.com/bootstrap-material-design@4.1.1/dist/css/bootstrap-material-design.min.css" integrity="sha384-wXznGJNEXNG1NFsbm0ugrLFMQPWswR3lds2VeinahP8N0zJw9VWSopbjv2x7WCvX" crossorigin="anonymous"> <script src="http://code.jquery.com/jquery-3.5.1.min.js"></script> </head> <style> .container { margin: 0 auto; margin-top: 200px; display: flex; flex-direction: column; align-items: center; font-size: 30px; } </style> <script> $(document).ready(function(){ $(document).click(function(){ var val = $(event.target).closest('#btn1').length; if(val){ $('.alert-warning').text("ボタンAがクリックされました"); }else{ $('.alert-warning').text("ボタンA以外がクリックされました"); } }); }); </script> <body> <div class="container"> <div class="alert alert-warning" role="alert"> </div> <button type="button" id="btn1" class="btn btn-raised btn-primary">ボタンA</button> <button type="button" id="btn2" class="btn btn-raised btn-danger">ボタンB</button> <button type="button" id="btn3" class="btn btn-raised btn-warning">ボタンC</button> </div> </body> </html> |
実行結果を見ると、ボタンAとそれ以外がクリックされたイベントが正しく取得されていることが確認できます。

-
前の記事
Nuxt.js ライブラリ「vue-slider-component」をインストールしてスライダーを実装する 2020.08.16
-
次の記事
php ライブラリ「ramsey/uuid」を使ってUUIDを生成する 2020.08.17
コメントを書く