jquery使用waypoint获取元素的id

我使用jquery waypoints( http://imakewebthings.com/jquery-waypoints/#docs )检查一个元素是否是浏览器的视图,这里是html:

1. Container
2. Container
3. Container
4. Container

这里是js

 $('#container_1').waypoint(function() { console.log("container 1 is visible"); }); 

这很好用!

但是有可能找出视图中的元素的当前id并且路点被触发吗? 像这样的东西:

 $('.container').waypoint(function() { console.log("id of element: " + $(this).attr('id'); }); 

谢谢!

你在console.log的末尾缺少括号:),否则它会起作用。

 $('.container').waypoint(function() { console.log("id of element: " + $(this).attr('id')); }); 

如果你感到困惑,你也可以这样使用:

 $('.container').waypoint(function() { var $this = $('.container'); console.log("id of element: " + $this.attr('id')); }); 

在waypoints.js中,我发现this是指一个航路点内部对象。 如果你使用console.log,你很容易找到如何用jquery选择那个元素。

 handler: function (direction){ var DOMElement = $(this.element); console.log($(this.element).attr('data-id'); } 

另外… 元素属性ID返回undefined