Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jquery控制台读取top属性时出错_Javascript_Jquery - Fatal编程技术网

Javascript jquery控制台读取top属性时出错

Javascript jquery控制台读取top属性时出错,javascript,jquery,Javascript,Jquery,我在努力解决一些问题。我有jquery代码,得到错误:uncaughttypeerror:无法读取未定义的属性“top”。我无法修复此问题 我的代码 <script> $('a').click(function(){ $('html, body').animate({ scrollTop: $( $(this).attr('href') ).offset().top }, 300); return fal

我在努力解决一些问题。我有jquery代码,得到错误:uncaughttypeerror:无法读取未定义的属性“top”。我无法修复此问题

我的代码

<script>
    $('a').click(function(){
        $('html, body').animate({
            scrollTop: $( $(this).attr('href') ).offset().top
        }, 300);
        return false;
    });
</script>

$('a')。单击(函数(){
$('html,body')。设置动画({
scrollTop:$($(this.attr('href')).offset().top
}, 300);
返回false;
});

我真的很感谢你的帮助

offset返回
undefined
的唯一原因是在空jQuery集合上调用它。这告诉我们,
$($(this.attr('href'))
找不到任何元素-例如,
$(this.attr('href')
在运行时与任何元素都不匹配。

根据我的理解(因为没有HTML标记),您的
href
值没有下面的
符号

 <a href="top">LINK</a>
 <a href="#top">LINK</a>

你可以在这里查看更新的

下面的代码片段。

$('a')。单击(函数(){
$('html,body')。设置动画({
scrollTop:$('#'+$(this.attr('href')).offset().top
}, 300);
返回false;
});

这里有东西

这里有东西

这里有东西

这里有东西

这里有东西

这里有东西

这里有东西

这里有东西

这里有东西

这里有东西这里有东西在这里有东西在这里有东西在这里有东西在这里有东西在这里有东西在这里有东西在这里有东西在这里有东西在这里有东西在这里有东西在这里有东西在这里这里

这里有东西

这里有东西

这是主分区
post-html标记alsoCome on!您无法获取
offset()。
href
@Mr.x的top
:如果
href
是散列片段链接,它也是一个ID选择器。例如,
表示
。attr(“href”)
“#foo”
,它将选择一个具有
id=“foo”
的元素。这并不少见。如果可以使用
$(this.offset().top
$('a#someId').offset().top
为什么要使用
href
,听起来这是一种选择元素的糟糕方法@T.J。Crowder@Mr.x:
$(this).offset().top
将告诉您链接顶部的位置
$($(this.attr(“href”)).offset().top
告诉您它链接到的元素的顶部在哪里。再说一次,这一点也不奇怪。这里唯一的问题是OP在一个链接上使用它,
#whatever
在DOM中没有匹配的元素。您正在推测href选择器不匹配的原因,但这是合理的推测。这里没有什么可以否决的。
  $('a').click(function(){        
    $('html, body').animate({
        scrollTop: $('#' + $(this).attr('href') ).offset().top
    }, 300);
    return false;
});