我正在更改我的一个项目的结构,但我无法弄清楚为什么我的新代码没有向我的元素添加类。
原代码是这样的
(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/