0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【jQuery】クリックイベント内でsetTimeoutで遅延実行する際のthisがうまく働かない

Posted at

要約

  1. $.proxy(function, context)を使う
  2. contextにthisと書いて対象オブジェクトを引き継ぐ
  3. setTimeout($.proxy(function(){実行したいこと},this), 1000)
  4. $object = thisを記述した方がわかりやすいのは自分だけ?

setTimeoutを使うとthisはそのままだと使用できない

エラーになるバージョン
    $('.unselected').click(function() {
        setTimeout(function(){
            $(this).removeClass('unselected');
        },1000);
    });
エラー回避バージョン
    $('.unselected').click(function() {
        setTimeout($.proxy(function(){
            $(this).removeClass('unselected');
        } ,this),1000);
    });

$.proxyでthisのとなるオブジェクトを引数として渡す

$.proxy(function, context)
function: 対象となる関数
context: functionの中でthisとなるオブジェクト

$.proxy(function(){}, this);
とすれば、直前のオブジェクトをthisで$.proxyの中のfunctionにthisとしたいオブジェクト渡すことができる。

オブジェクトを別の変数で受け取ってから渡してもいい
    $('.unselected').click(function() {
        // 遅延実行したい対象のオブジェクト
        $object = this; 
        // 対象のオブジェクトを$.proxyの第二引数に引き継いで上げる
        setTimeout($.proxy(function(){
            $(this).removeClass('unselected');
        } ,$object),1000);
    });

これでクリックされたものだけイベントが発生するようになる。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?