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

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

最佳答案

您需要指向正确的this

更新自

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

$this.addClass("active");

关于javascript - 为什么类没有添加到我的元素中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52589395/

相关文章:

javascript - CSS 转换不影响替换节点

javascript - 使用 Bootstrap 表获取 'a' 元素的 id

JavaScript - 静态变量?

javascript - 向 slider 添加触摸选项

python - 使用 Ajax 验证并提交 Django 表单 (django-crispy-forms)

jquery - 使用jquery解析html和文本的比较

html - IE9标题栏只显示域名不显示页面标题

html - 多列和收缩包装

javascript - Reacts `propTypes` 和 `defaultProps` 应该和 Flowtype 一起使用,还是 Flowtype 够全面?

c# - 将 Hashalgorithm 与 ReadOnlySpan<byte> 结合使用