"这"将不会引用JQuery侦听器中的div [英] "this" won't refer to the div in a JQuery listener
问题描述
我有一个类 .my-class
的下面的监听器(我正在使用航点插件)。但是,如果我尝试调用 $(this).addClass(hello)
,它不会将该类添加到单个 div
具有该类并触发了侦听器。如果我调用
$(。my-class)。addClass(hello)
在函数内部,它将类 hello
添加到 .my-class
的所有实例中,这不是我想要什么。
我误解了这个
应该如何使用(我是JS的新手) ?它不应该引用触发侦听器的单个 div
,因此将该类添加到该div中?
$(。my-class)。waypoint(function(e){
$(this).addClass(hello);
})
当使用 waypoint
,这个
引用航点对象。航点对象的元素是当前的div。所以你会想要使用
$(。my-class)。waypoint(function(e){
$(this.element).addClass(hello);
})
I have the below listener for a class .my-class
(I'm using the waypoint plugin). However, if I try to call $(this).addClass("hello")
, it does not add the class to the individual div
that has the class and fired the listener.
On the other hand, if I call $(".my-class").addClass("hello")
inside the function instead, it adds the class hello
to ALL instances of .my-class
, which is not what I want.
Am I misinterpreting how this
is supposed to be used (I'm new to JS)? Shouldn't it refer to the single div
that fires the listener and therefore add the class to that div?
$(".my-class").waypoint(function(e) {
$(this).addClass("hello");
})
When using waypoint
, this
refers to the waypoint object. The waypoint object's element is the current div. So you would want to use
$(".my-class").waypoint(function(e) {
$(this.element).addClass("hello");
})
这篇关于"这"将不会引用JQuery侦听器中的div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!