javascript Jquery $(this) 在函数内部不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31968289/
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
Jquery $(this) not working inside function
提问by ServerSideSkittles
I am trying to use waypoints.js to have elements fadein when scrolling to hit the elements.
我正在尝试使用 waypoints.js 在滚动以点击元素时让元素淡入淡出。
I have
我有
$(document).ready(function(){
$('.card').waypoint(function(down) {
console.log('hit element');
$(this).addClass('card-fadeIn');
}, { offset: '100%' });
});
What this does is adds the class 'card-fadeIn' which is opacity 1 and an ease in animation.
这样做是添加了类“card-fadeIn”,它是不透明度 1 和动画的缓和。
When I change it to
当我把它改成
$('.card').addClass('card-fadeIn');
It works fine, but adds opacity 1 to every card class and ruins the fadein effect. I was trying to use $(this) instead but it wont fadein, nor will it give an error in the console. Any ideas why?
它工作正常,但为每个卡片类添加不透明度 1 并破坏淡入效果。我试图使用 $(this) 代替,但它不会淡入淡出,也不会在控制台中出现错误。任何想法为什么?
回答by Pointy
You have to use
你必须使用
$(this.element)
in a Waypoint handler. So,
在航点处理程序中。所以,
$(this.element).addClass('card-fadeIn');
should do what you want.
应该做你想做的。
$(this)
works inside jQuery callbacks because jQuery is designed for things to work that way. There's nothing magic about it, however, so if this
doesn't refer to a DOM element, you'll get a jQuery object that won't do anything (and which won't report any errors, because, again, that's just how jQuery works). The Waypoint library binds this
to its own context object, and that exposes a reference to the DOM element involved in the callback as the "element" property.
$(this)
在 jQuery 回调中工作,因为 jQuery 是为以这种方式工作而设计的。然而,它this
并没有什么神奇之处,所以如果不引用 DOM 元素,您将得到一个 jQuery 对象,它不会做任何事情(并且不会报告任何错误,因为再一次,这就是 jQuery作品)。Waypoint 库绑定this
到它自己的上下文对象,并将回调中涉及的 DOM 元素的引用公开为“元素”属性。
回答by Dennis
Have you tried this.element?
你试过 this.element 吗?
$(document).ready(function(){
$('.card').waypoint(function(down) {
console.log('hit element');
$(this.element).addClass('card-fadeIn');
}, { offset: '100%' });
});