jQuery scrollTop动画返回Uncaught TypeError

时间:2013-11-03 14:03:40

标签: javascript jquery html jquery-animate

我的jQuery代码出现问题(如下所示),我不明白为什么?

我正在尝试给我的网站一个scrollTop动画,它正常工作正常,但是当我想使用ul li ul li a星座时,即使jQuery,它也会被卡住,我会收到错误像这样:

Uncaught TypeError: Cannot read property 'top' of undefined

我有一个小提琴我的代码和完全相同的情况:当我点击例如href="#5.1"

更新代码:

$('ul li a').click(function(event) {
    var location = $(this).attr('href');
    $('html, body').animate({
        scrollTop : $(location).offset().top -10
    }, 800, function () {
       var location 2 = location.replace( "\\" ,"");
    window.location.hash = location2;
});
    return false;
});

jsFiddle Example

1 个答案:

答案 0 :(得分:3)

您的解决方案很直接!你必须逃避.,就像这样:

<a href="#5\.1">Punkt 10: Header und Footer ohne ID ansprechen</a>

Online Working Example

  

使用任何元字符(例如   !“#$%&amp;'()* +,。/:;&lt; =&gt;?@ [] ^`{|}〜)作为名称的字面部分,必须   逃脱。

Selectors | jQuery API Documentation

编辑1:

如果您尝试避免在实际网址中使用\,只需尝试删除它,方法是将简单的正则表达式应用于您的位置变量:

var location = location.replace(/\\/g,"");