Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

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

結論

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 
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away