3

Bootstrapと相互作用するjQueryプラグインを作成していますが、jQuery要素で関数を呼び出すと次のエラーが発生します。

Uncaught TypeError: Object [object Window] has no method 'each' 

これは問題のJavaScriptです:

!function ($) {
$.fn.alertAutoClose = function (interval) {
  setTimeout(function () {
    return $(this).each(function () {
      $(this).hide();
    });
  }, interval);
}(window.jQuery);

プラグインは次のようにトリガーされます。

$(".alert").alertAutoClose(1000);

これはページ上のHTMLです:

<div class="alert fade in">
  <button type="button" class="close" data-dismiss="alert">&times;</button>
  <strong>Warning!</strong> Best check yo self, you're not looking too good.
</div>
4

1 に答える 1

1

の内部は、setTimeout()あなたのオブジェクトではありません。参照を保存して、次のようなことを行う必要があります。thiswindowthis

!function ($) {
$.fn.alertAutoClose = function (interval) {
     var self = this;
     setTimeout(function () {
       self.hide();
     }, interval);
     return this;
}(window.jQuery);

参考までに、次のように同じことを実行することもできます。

!function ($) {
$.fn.alertAutoClose = function (interval) {
     this.delay(interval).hide(1);
     return this;
}(window.jQuery);

期間を.hide()指定すると、アニメーションに変わるため、で機能し.delay()ます。

また、thisjQueryメソッド内の値はjQueryオブジェクトです。したがって、jQueryオブジェクトのすべての要素に適用されるメソッドを呼び出す場合は、で直接メソッドを呼び出すことができますthis。これをjQueryオブジェクト(すでに1つ)に変換する必要はありません。.each()また、ほとんどのjQueryメソッド(.hide()オブジェクト内のすべての要素に対して既に動作しているなど)を使用する必要もありません。

于 2012-10-03T03:02:41.120 に答える