插件在 jQuery 2.2.0 更新后停止工作

Plugin stopped working after jQuery 2.2.0 update

本文关键字:停止工作 更新 jQuery 插件      更新时间:2023-09-26

我有小的scrollspy片段来观察DOM中的滚动事件

代码段在 jQuery 2.1.4 之前工作正常,但在最新的 jQuery 2.2.0 中不起作用

代码如下:

// Cache selectors
var lastId,
    topMenu = $("#top-menu"),
    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 click handler to menu items
// so we can get a fancy scroll animation
menuItems.click(function(e){
  var href = $(this).attr("href"),
      offsetTop = href === "#" ? 0 : $(href).offset().top-topMenuHeight+1;
  $('html, body').stop().animate({ 
      scrollTop: offsetTop
  }, 300);
  e.preventDefault();
});
// 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");
   }                   
});

我尝试调试,但它抛出

Error: Syntax error, unrecognized expression: [href=#baz]

这是jsFiddle: http://jsfiddle.net/up4nu/5473/

最新的jQuery 2.2.0中的哪些更新一定导致了此错误?

您需要转义#符号。演示。

end().filter("[href='"#"+id+"'"]").parent().addClass("active");

或者,您可以使用''# .演示。

end().filter("[href=''#"+id+"]").parent().addClass("active");