javascript 未捕获的类型错误:无法使用 IIFE 读取未定义的属性“defaultView”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23146160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uncaught TypeError: Cannot read property 'defaultView' of undefined with a IIFE
提问by Kenneth .J
I'm working my way through Learning jQuery 4th Edition (PacktPub publishing), trying out one of it's exercises where i have to create new plugin methods called .slideFadeIn() and .slideFadeOut(),combining the opacity animations of .fadeIn() and .fadeOut() with the height animations of .slideDown() and .slideUp().
我正在学习 jQuery 第 4 版(PacktPub 发布),尝试其中一个练习,我必须创建名为 .slideFadeIn() 和 .slideFadeOut() 的新插件方法,结合 .fadeIn() 的不透明度动画和 .fadeOut() 与 .slideDown() 和 .slideUp() 的高度动画。
This is my current code
这是我当前的代码
(function($) {
$.fn.slides={
slideIn:function(){
$(this).fadeIn().slideDown();
},
slideOut:function(){
$(this).fadeOut().slideUp();
}
}
})(jQuery);
$('h1').click(function(){
$(this).slides.slideOut();
});
yet when i click on <h1>
, i get the error message,
但是当我点击时<h1>
,我收到错误消息,
Uncaught TypeError: Cannot read property 'defaultView' of undefined
I've also tried
我也试过
(function($) {
var elem=$(this);
$.fn.slides={
slideIn:function(){
elem.fadeIn().slideDown();
},
slideOut:function(){
elem.fadeOut().slideUp();
}
}
})(jQuery);
to see if the error was because $(this)
was referring to a different context, but i am still getting the same error
查看错误是否是因为$(this)
指的是不同的上下文,但我仍然遇到相同的错误
Uncaught TypeError: Cannot read property 'defaultView' of undefined
EDIT:I've tried editing the code to
编辑:我试过编辑代码
$('h1').fadeOut().slideUp();
and it works, so the issue lies with $(this)
, i just don't see what exactly is the problem with $(this)
它有效,所以问题在于$(this)
,我只是不明白到底是什么问题$(this)
Could someone kindly point out my mistake?
有人可以指出我的错误吗?
Thanks!
谢谢!
采纳答案by james emanon
The way you are creating your plugin is a little different than I would, as the "this" is the "fn.slides" scope 'this' - thus, it errors out. I was able to solve your issue by passing the context of the "this" you want -- which is the 'h1' by using 'call'. With "call" (and "apply), I can call the function and pass in the 'this' context I want.
您创建插件的方式与我的方式略有不同,因为“this”是“fn.slides”范围“this” - 因此,它会出错。我能够通过传递您想要的“this”的上下文来解决您的问题 - 这是使用“call”的“h1”。通过“调用”(和“应用”),我可以调用函数并传入我想要的“this”上下文。
(function($) {
$.fn.slides={
slideIn:function(){
$(this).fadeIn().slideDown();
},
slideOut:function(){
$(this).fadeOut().slideUp();
}
}
})(jQuery);
$('h1').click(function(){
$(this).slides.slideOut.call(this);
});