我的站点上的所有内容都运行良好,但出于某种原因,每当我单击站点上任意位置的链接时,我都会在控制台中收到一条错误消息。该错误与此处的这行代码有关:
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’的值:对象为空或未定义 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/
然后单击其中一个过滤器按钮。
最终,我试图做到这一点,以便我的滚动到设置仍然有效,但不再出现该错误。我很久以前制作了这个脚本,但我真的很困惑,如果一切都运行良好,会导致这个错误吗?
谢谢!
最佳答案
您遇到的问题是,给出错误的代码用于滚动到预定义的 div,并且您在 url 的 hashtag 中有它的 id(目标 div)(单击链接的 href 属性)。
当你点击“正常”链接时,这是个问题,因为它不包含页面上现有元素的标签,所以 $($anchor.attr('href'))
给出空数组,因为没有这样的元素可以用 $("http://www.northtownsremodeling.com/alliances.php")
来选择,所以,在那种情况下 offset() 是undefined 并给你一个错误。
要解决此问题,请替换:
$('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');
}
关于javascript - 每次单击链接时都会出现脚本错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12488124/