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");
})
From the api docs, they have a snippet like this:
var waypoints = $('#options-only').waypoint({
handler: function(direction) {
notify(this.element.id + ' hit')
}
})
so you might need to do $(this.element), or maybe this.element is already a jquery object? I don't know much about waypoint.
来源:https://stackoverflow.com/questions/27726357/this-wont-refer-to-the-div-in-a-jquery-listener