Javascript 在滚动偏移脚本中未定义preventDefault

Javascript 在滚动偏移脚本中未定义preventDefault,javascript,jquery,scroll,offset,preventdefault,Javascript,Jquery,Scroll,Offset,Preventdefault,我正在使用此脚本滚动到锚点: $( document ).ready(function(e) { var $root = $('html, body'); $('a').click(function(e) { e.preventDefault(); var href = $.attr(this, 'href'); if(href!=='javascript:void(0)' && href!=='javascri

我正在使用此脚本滚动到锚点:

$( document ).ready(function(e) 
{
    var $root = $('html, body');
    $('a').click(function(e) {
        e.preventDefault();
        var href = $.attr(this, 'href');

        if(href!=='javascript:void(0)' && href!=='javascript:void(0);'){
            $root.animate({
                scrollTop: $(href).offset().top-100
            }, 1000, function (e) {
                e.preventDefault();
                window.location.hash = href;
            });
            return false;
        }
    });

});
但是,在单击链接(动画完成)后,我两次出现以下错误:
uncaughttypeerror:cannotreadproperty'preventDefault'of undefined

我不明白为什么。我试图将
e
添加到函数中,但它仍然给出了错误。有人能提供一些背景资料吗?

问题是

$( document ).ready(function(e) 
{
    var $root = $('html, body');
    $('a').click(function(e) {
        e.preventDefault();
        var href = $.attr(this, 'href');

        if(href!=='javascript:void(0)' && href!=='javascript:void(0);'){
            $root.animate({
                scrollTop: $(href).offset().top-100
            }, 1000, function (e) {
//                             ^−−−−−−−−−−−−−−−−−−−−−− here
                e.preventDefault();             // <−− and/or (arguably) here
                window.location.hash = href;
            });
            return false;
        }
    });

});

您添加了
e.preventDefault()
.animate
回调函数。您希望它做什么?问题是,由于scroll to元素的偏移量为
-100
,因此页面在更新URL后会有一点跳跃。我想阻止它,这就是为什么我有这个
e.preventDefault()
动画
回调中。如果我删除它,它仍然会做出这种奇怪的跳跃。@Jordy那么也许这会有用:@Jordy-我在答案的底部添加了对该评论的回应。
history.replaceState(null, "", href);