【问题标题】:Uncaught TypeError: Object [object Window] has no method 'each'未捕获的类型错误:对象 [对象窗口] 没有方法“每个”
【发布时间】:2012-10-03 02:57:13
【问题描述】:

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

【问题讨论】:

    标签: javascript jquery plugins window each


    【解决方案1】:

    setTimeout()this 的内部是 window,而不是你的对象。您需要保存 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() 已经对对象中的所有元素进行了操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-05
      • 1970-01-01
      • 2014-05-12
      相关资源
      最近更新 更多