“this” won't refer to the div in a JQuery listener

孤街浪徒 提交于 2019-12-31 03:28:06

问题


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");
})

回答1:


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");
})



回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!