LoginSignup
12
13

More than 5 years have passed since last update.

jQueryで設定したイベントのバブリングと実行順について

Last updated at Posted at 2014-04-28

実行順わかんなくなるのでメモ。

結論

jQueryはバブリングフェーズにイベントが設定されるので、発生した要素から順に親要素へイベントが伝播する。
1つの要素に複数のイベントが設定されていた場合、delegateTarget内でバブリングし、さらにその内部でtarget内でバブリングする。

ちなみにonメソッドの引数にセレクタを指定した場合は、jQueryオブジェクトの選択要素の内部に含まれる要素に対して設定される。

バブリングした要素に同じクラス属性が指定されていたりすると、2回実行されるのが意外と気づかなくてバグったりするので気を付ける。

テストコード

<div class="c1">
<button type="button" class="c1">click me!</button>
</div>
$(document).on("click", "button", function(e){
    console.log("document button");
});
$(document).on("click", "div", function(e){
    console.log("document div");
});
$(document).on("click", ".c1", function(e){
    console.log("document class:c1");
});
$("div").on("click", "button", function(e){
    console.log("div button");
});
$("div").on("click", "div", function(e){
    console.log("div div");
});
$("div").on("click", ".c1", function(e){
    console.log("div class:c1");
});
$("div").on("click", function(e){
    console.log("div");
});
$(".c1").on("click", function(e){
    console.log("class:c1");
});
$("button").on("click", function(e){
    console.log("button");
});

結果

class:c1
button
div button
div class:c1
div
class:c1
document button
document class:c1
document div
document class:c1 
12
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
13