活动导航项

问题描述 投票:0回答:2

当用户滚动到某个div时,我有一些代码可以将类active添加到导航中。我也使用vue.js并且有一些不使用导航的组件。在这些组件中(我不使用导航)我收到错误:Uncaught TypeError: Cannot read property 'top' of undefined代码:

$(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;
   }
javascript navigation
2个回答
1
投票

检查元素是否未定义

if($($(this).attr('href')).offset() != undefined && y >= $($(this).attr('href')).offset().top)

我编辑了这个答案:

.each(function(index, element){})

你可以在这里看到event这里只是变量的名称,如果它登录到控制台你会发现它代表索引$('.link').each(function (event){})所以event.length是无意义的ref:。 https://api.jquery.com/each/

  • .link选择器倾向于收集锚链接
  • $($(this).attr('href')) <a href="#selectorId">menu item</a>所以,如果你的元素没有href与偏移如果会抛出undefined

1
投票

看来你希望`event'成为这段代码中的集合:

   if(!event.length) {
     return;
   }

这段代码:

$('.link').each(...)

传递来自$('.link'), and it appears that single item should be and HTMLAnchorElement. The HTMLAnchorElement does not have alengthproperty. The length property comes through the inheritance heirarchy for the`标签创建的jQuery集合中的单个项目。

https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement

看来你的意图可能是在伪代码中做这样的事情:

  1. 抓取所有链接(将它们放入集合中)
  2. 如果没有链接(集合的长度为零)不要做任何事情
  3. 否则(有链接)对于每个链接,找到要突出显示的那个将active类添加到该元素

这不是你的代码所做的。

请让我知道,如果你有任何问题。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.