将菜单项与滚动绑定时出现Jquery错误

Jquery error when binding menu item with scrolling

本文关键字:Jquery 错误 定时 绑定 菜单项 滚动      更新时间:2023-09-26

我尝试将导航菜单与滚动绑定。效果:当我滚动窗口浏览器时,活动菜单项将高亮显示。

这是html:

<ul class="navigation">
    <li><a href="#intro">HOME</a></li>
    <li><a href="#anchor1">Link 1</a></li>
    <li><a href="#anchor2">Link 2</a></li>
    <li><a href="#anchor3">Link 3</a></li>
    <li><a href="#anchor4">Link 4</a></li>
    <li><a href="#anchor5">Link 5</a></li>
    <li><a href="http://localhost/pages/blog/">BLOG</a></li>
</ul>

jquery代码为:

$(window).load(function(){
// Cache selectors
var lastId,
    topMenu = $(".navigation"),
    topMenuHeight = topMenu.outerHeight()+15,
    // All list items
    menuItems = topMenu.find("a"),
    // Anchors corresponding to menu items
    scrollItems = menuItems.map(function(){
      var item = $($(this).attr("href"));
      if (item.length) { return item; }
    });
// Bind to scroll
$(window).scroll(function(){
   // Get container scroll position
   var fromTop = $(this).scrollTop()+topMenuHeight;
   // Get id of current scroll item
   var cur = scrollItems.map(function(){
     if ($(this).offset().top < fromTop)
       return this;
   });
   // Get the id of the current element
   cur = cur[cur.length-1];
   var id = cur && cur.length ? cur[0].id : "";
   if (lastId !== id) {
       lastId = id;
       // Set/remove active class
       menuItems
         .parent().removeClass("active")
         .end().filter("[href=#"+id+"]").parent().addClass("active");
   }                   
});

此错误出现在firbug控制台上:

Error: Syntax error, unrecognized expression: http://localhost/pages/blog/

我发现代码无法处理abslolute url:

var item = $($(this).attr("href")); 

然后我把它换成:

var item = $(this).attr('href').split('=');

现在这个错误已经显示:

    TypeError: $(...).offset(...) is undefined
if ($(this).offset().top < fromTop)

注意,当我删除html行时:

<li><a href="http://localhost/pages/blog/">BLOG</a></li>

一切进展顺利。但有了它,这些错误就发生了,菜单滚动影响就不会发生。

你知道问题出在哪里吗?我该如何解决?

经过两天的搜索并试图了解问题所在,我解决了它。(请参阅本页作为我的解决方案的资源

在jquery:中替换此代码

scrollItems = menuItems.map(function(){
  var item = $($(this).attr("href"));
  if (item.length) { return item; }
});

使用此代码:

// Anchors corresponding to menu items
scrollItems = menuItems.map(function(){
  var indexItm = $(this).attr('href').indexOf('#');
  if (indexItm >= 0) {
    var str = $(this).attr('href').substring(indexItm);
    var item = $(str);
    if (item.length) { return item; }
    }
})
;

仅此而已。

var item=$($(this).attr("href"));在代码中创建了问题,因为当您编写href="#id"时,它是var item=$(#id);但当你写href="/blog/"时,它变成了var item=$(/blog/);这是不正确的。