我有一些代码可以在用户滚动到某个 div 时将 active
类添加到导航中。我还使用 vue.js 并有一些不使用导航的组件。在这些组件中(我不使用导航)我收到错误:
未捕获类型错误:无法读取未定义的属性“top”
代码:
$(document).ready(function () {
$(window).scroll(function () {
var y = $(this).scrollTop();
$('.link').each(function (event) {
// this code allows me to disable script when there's no navigation
if(!event.length) {
return;
}
if (y >= $($(this).attr('href')).offset().top) {
$('.link').not(this).removeClass('active');
$(this).addClass('active');
}
});
});
});
这段代码允许我在没有导航时禁用脚本,但它也会破坏其余的代码,因此在带有导航的主页上,没有添加类。
if(!event.length) {
return;
}
最佳答案
检查元素是否未定义
if($($(this).attr('href')).offset() != undefined && y >= $($(this).attr('href')).offset().top)
我编辑了这个答案:
.each(function(index, element){})
你可以在这里看到event
这里只是变量的名称,如果它登录到控制台,您会发现它代表索引 $('.link').each(function (event){})
所以event.length
毫无意义
引用:。 https://api.jquery.com/each/
-
.link
选择器往往用于 anchor 链接的集合 -
$($(this).attr('href'))
<a href="#selectorId">menu item</a>
所以如果你的元素没有href
如果带有偏移量,则会抛出undefined
关于javascript - 事件导航项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49078086/