LoginSignup
26
27

More than 5 years have passed since last update.

setTimeout内でjQueryの$(this)を使う場合の注意点

Posted at

問題点

setTimeoutは、一定時間後に渡された関数を実行する関数です。
今回、このsetTimeoutに渡した関数内でjQueryの$(this)を使ったらエラーになりました。

Uncaught TypeError: Cannot call method 'toLowerCase' of undefined

解決方法

$.proxyをかませば問題なく動作しました。

javascript
$("#bar").click(function(){
  setTimeout($.proxy(function(){
    $("#foo").load('/foo/bar', {value: $(this).val()});
  }, this), 1000);
});

$.proxyメソッドは、渡された関数内のthisを第二引数にすることができるというものです。

参考URL

26
27
2

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
26
27