我正在创建一个与 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">×</button>
<strong>Warning!</strong> Best check yo self, you're not looking too good.
</div>
最佳答案
在 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()
已经对对象中的所有元素进行了操作。
关于javascript - 未捕获的类型错误 : Object [object Window] has no method 'each' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12701301/