将菜单项与滚动绑定时出现Jquery错误
Jquery error when binding menu item with scrolling
我尝试将导航菜单与滚动绑定。效果:当我滚动窗口浏览器时,活动菜单项将高亮显示。
这是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/);这是不正确的。
相关文章:
- 将菜单项与滚动绑定时出现Jquery错误
- 试图获取表单时出现Jquery错误
- 任何人都知道IE7设置或更新/补丁,它可以防止IE因为jquery错误而无法加载页面
- 组中需要Jquery错误位置
- IE9中的Jquery错误
- 使用下拉菜单排除jquery错误
- 在文本区域检查电子邮件数据时出现奇怪的jquery错误
- 扩展对象导致jQuery错误
- 一个经典的jQuery错误 - 未捕获的类型错误:未定义不是一个函数
- 使用ng-include时发生Angular.js jQuery错误
- JQuery 错误 -- 减慢在浏览器中查看错误的操作速度
- 在页面上获取网格数据之前出现 jQuery 错误
- 如何修复我的 JQuery 错误
- jQuery 错误 SCRIPT5002:IE9 64 位中预期的函数
- jQuery错误地导致悬停
- 未定义获取 jquery 错误 $
- 将 jQuery 错误处理添加到列表、网格内的 JSF 页面上的所有图像
- 未捕获的错误:信号器 jquery 错误
- JQuery 错误的脚本顺序
- 当展开点击 li 的 ul 事件时,JS JQUERY 错误不起作用