为什么没有将类添加到我的元素中?

时间:2018-10-01 10:42:09

标签: javascript jquery html

我正在更改我的一个项目的结构,我无法弄清楚为什么我的新代码没有在元素中添加类。

原始代码是这个

(function($)
{
    var $nav = $('#nav');

    var $nav_a = $nav.find('a');

    $nav_a.each(function()
    {
        var $this = $(this),
        id = $this.attr('href'),
        $section = $(id);

        $section.scrollex(
        {
            mode: 'middle',

            enter: function()
            {
                $nav_a.removeClass('active');
                $this.addClass('active');
            }
        });
    });
})(jQuery);

我的新代码是这个

$("#nav").find("a").each(function(){
    var $this = $(this),
        id = $this.attr('href'),
        $section = $(id);

    $section.scrollex({
        mode: "middle",

        enter: function()
        {
            $("#nav").find("a").removeClass("active");

            $(this).addClass("active");
        }
    })
});

新代码无法将类active添加到#nav中的元素,但是原始代码可以正常工作。我的新代码在做什么错了?

2 个答案:

答案 0 :(得分:2)

您需要指向正确的Ctrl+Alt+L

更新自

this

$(this).addClass("active");

答案 1 :(得分:1)

您的代码存在问题是您将$(this)分配给$this,因此,当您以后使用$(this)时,实际上是在使用$$(this)

在以下行中替换变量:

$(this).addClass("active");

$this.addClass("active");