javascript - 每次单击链接时都会出现脚本错误

标签 javascript jquery html navigation anchor

我的站点上的所有内容都运行良好,但出于某种原因,每当我单击站点上任意位置的链接时,我都会在控制台中收到一条错误消息。该错误与此处的这行代码有关:

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/

相关文章:

带有 DOM 事件处理程序的 Javascript 运算符不起作用

php - 即使session_start()已经在最前面,“session_start(): Cannot send session cache limiter - headers already sent”仍会继续出现

javascript - 将保存在变量中的像素数量添加到 jQuery 中的 css 属性

javascript - Laravel 5.3 中的脚本文件包含

javascript - HTML onClick 不会在右键单击时触发

javascript - jQuery 模糊事件未在隐藏元素上触发

javascript - 将计算值从弹出菜单传输到主窗体

javascript - jQuery 表达式 $ ('a[href*=#]:not([href=#])' ) 针对哪些元素?

javascript - Android 使用 Hyphenator.js 完全对齐和自动断字

html - 试图将图像包含在另一个图像中