本文介绍了元素属性ID返回未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用waypoints.js并在用户滚动到菜单元素时使菜单元素处于活动状态.如我所见,航路点效果很好,但我无法获得当前部分id ...控制台始终说undefined.

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?

我的脚本是:

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%'
    });
});

我的HTML nav是:

<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>

我的HTML section是:

<section id="home">
    <div class="wrap">
        <h1>...</h1>
    </div>
</section>

推荐答案

在waypoints.js中,我发现this引用了一个Waypoints内部对象.如果您进行console.log记录,则可以轻松找到如何使用jquery选择该元素.

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

这篇关于元素属性ID返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-30 08:09