jQuery $(this)在函数内部不起作用 [英] Jquery $(this) not working inside function

查看:97
本文介绍了jQuery $(this)在函数内部不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用waypoints.js在滚动以击中元素时使元素淡入.

I am trying to use waypoints.js to have elements fadein when scrolling to hit the elements.

我有

$(document).ready(function(){

$('.card').waypoint(function(down) {
    console.log('hit element');
    $(this).addClass('card-fadeIn');
}, { offset: '100%' });

});

这是添加不透明度1并简化动画处理的类"card-fadeIn".

What this does is adds the class 'card-fadeIn' which is opacity 1 and an ease in animation.

当我将其更改为

$('.card').addClass('card-fadeIn');

它可以正常工作,但会为每个卡片类别增加不透明度1,并破坏淡入效果.我试图改用$(this),但它不会淡入,也不会在控制台中给出错误.有什么想法吗?

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?

推荐答案

您必须使用

$(this.element)

在Waypoint处理程序中.所以,

in a Waypoint handler. So,

$(this.element).addClass('card-fadeIn');

应该做你想做的事.

$(this)可在jQuery回调中使用,因为jQuery专为以这种方式工作的事物而设计.但是,这没有什么魔术,因此,如果 this 不引用DOM元素,您将获得一个不会执行任何操作的jQuery对象(并且该对象不会报告任何错误,因为,这又是jQuery的工作方式).Waypoint库将 this 绑定到其自己的上下文对象,并且将对回调中涉及的DOM元素的引用公开为"element"属性.

$(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.

这篇关于jQuery $(this)在函数内部不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆