未捕获的TypeError:对象[对象窗口]没有方法'每个'

时间:2012-10-03 02:57:14

标签: javascript jquery plugins window each

我正在创建一个与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>

1 个答案:

答案 0 :(得分:1)

setTimeout()内,thiswindow,而不是您的对象。您需要保存this引用并执行以下操作:

!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()一起使用。

此外,jQuery方法中的this值是jQuery对象。因此,如果要调用适用于jQuery对象中所有元素的方法,则可以直接在this上调用该方法。您不必将其转换为jQuery对象(它已经是一个),您不必使用.each(),因为大多数jQuery方法(如.hide())已经对对象中的所有元素进行操作