简体   繁体   中英

Why is a class not being added to my element?

I am changing the structure of one of my projects and I am unable to figure out why my new code is not adding a class to my element.

The original code is this

(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);

My new code is this

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

The new code fails to add the class active to the elements in #nav but the original code works fine. What am I doing wrong in my new code?

You need to point to the correct this

Update from

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

to

$this.addClass("active");

The problem with your code is that you assigned $(this) to $this , thus when you later use $(this) you are actually using $$(this) .

Replace the variable in the following line:

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

to

$this.addClass("active");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM