问题
I tried to work with waypoints.js
and make menu element active, when user scroll to it. As I can see, waypoints works well, but I can't get current section id
... Console always said undefined
.
So, what I'm doing wrong?
My script is:
jQuery(function() {
var sections = jQuery('section');
var navigation_links = jQuery('nav a');
sections.waypoint({
handler: function(direction) {
var active_section;
active_section = jQuery(this);
if (direction === "up") active_section = active_section.prev();
var active_link = jQuery('nav a[href="#' + active_section.attr("id") + '"]');
navigation_links.parent().removeClass("active");
active_link.parent().addClass("active");
active_section.addClass("active-section");
console.log(active_section.attr("id"))
},
offset: '35%'
});
});
My HTML nav
is:
<ul class="nav">
<li><a href="#home">Home</a></li>
<li><a href="#spec">What we do</a></li>
<li><a href="#features">Features</a></li>
<li><a href="#tools">Tools</a></li>
<li><a href="#contacts">Contacts</a></li>
</ul>
My HTML section
is:
<section id="home">
<div class="wrap">
<h1>...</h1>
</div>
</section>
回答1:
In waypoints.js I've found that this
refers to a waypoints internal object. If you console.log it though, you easily find how to select that element with jquery.
handler: function (direction){
var DOMElement = $(this.element);
console.log($(this.element).attr('data-id');
}
回答2:
As mentioned by @AmmarCSE the problem is indeed with if (direction === "up") active_section = active_section.prev();
. Basically if the previous element does not have an id
then undefined
will be printed in the console. A way to avoid this is to check that the previous element has an id
(check and make sure it's not undefined
), an only then set active_section
like so:
var prev_section_id = active_section.prev().attr("id");
if (direction === "up" && typeof prev_section_id != 'undefined')
active_section = active_section.prev();
Example Here
回答3:
This worked for me, only this will not return the id
$('.section').waypoint(function(){alert('this.element.id');});
来源:https://stackoverflow.com/questions/30816909/element-attribute-id-return-undefined