我的网站上的所有内容都运行得很完美,但出于某种原因,每当我点击网站上任何地方的链接时,我都会在控制台中收到错误消息。错误与此处的编码行有关:
jQuery(function($){
$('.navbar a, .scroll a, .smoothscroll a').bind('click',function(event){
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 850,'easeInOutExpo');
event.preventDefault();
});
});
我得到的错误是:
“SCRIPT5007:无法获取属性'top'的值:object为null或undefined custom.min.js,第6行,第197行“
它突出显示的确切代码是上述代码的一部分:
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 850,'easeInOutExpo')
我所知道的是,当我删除上面的代码时,我的滚动链接会停止在以下页面上工作:
http://www.northtownsremodeling.com/things-to-know.php
您可以通过转到包含以下过滤器的页面来查看弹出错误并轻松保留在控制台中:
http://www.northtownsremodeling.com/bathroom/
点击其中一个过滤按钮。
最终,我试图让它成为我的滚动设置仍然有效,但不再出现错误。很久以前我制作了这个剧本,我真的很困惑,当一切都运转正常时,可能导致这个错误的原因呢?
谢谢!
答案 0 :(得分:5)
你遇到的问题是,给出错误的代码是滚动到预定义的div,并且你在url的hashtag中有你的id(目标div)(点击链接的href属性)。
当你点击“普通”链接时会出现这个问题,因为它不包含hashpage,它是页面上存在的元素的id,所以$($anchor.attr('href'))
给出了空数组,因为没有这样的元素可以用即$("http://www.northtownsremodeling.com/alliances.php")
,所以,在这种情况下,offset()是未定义的,并给你一个错误。
要解决此问题,请替换:
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 850,'easeInOutExpo');
使用:
// get target div to scroll to
var target = $($anchor.attr('href'));
// if target is valid, scroll to
if(target && target.offset()){
$('html, body').stop().animate({
scrollTop: target.offset().top
}, 850,'easeInOutExpo');
}
答案 1 :(得分:1)
我认为这是因为href
属性不包含正确的选择器。如果链接符合ID为nav
的广告连播,则链接的href
属性应为#nav
。
您应该仅将事件处理程序绑定到导航链接。