Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/396.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么没有将类添加到我的元素中?_Javascript_Jquery_Html - Fatal编程技术网

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

Javascript 为什么没有将类添加到我的元素中?,javascript,jquery,html,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);

我正在更改我的一个项目的结构,我无法理解为什么我的新代码没有向元素添加类

原来的代码是

(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");
        }
    })
});
我的新代码是

(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
中的元素,但原始代码工作正常。我在新代码中做错了什么?

您需要指向正确的

更新自

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


您需要指向正确的

更新自

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


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

替换以下行中的变量:

$(this.addClass(“活动”);

$this.addClass(“活动”);

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

替换以下行中的变量:

$(this.addClass(“活动”);

$this.addClass(“活动”);