JavaScript - 无法读取 null 的属性“top" [英] JavaScript - Cannot read property 'top' of null

查看:48
本文介绍了JavaScript - 无法读取 null 的属性“top"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有滚动到列表中锚点位置的功能

I have function that scrolls to a anchor position in a list

   function snapToAnchor(anchor) {
    $('#divProductScroll').scrollTop(0);
    var offset = $(anchor).offset().top - $('#divProductScroll').offset().top;
    $('#divProductScroll').scrollTop(offset);
    //$('#divProductScroll').animate({ scrollTop: offset }, 250);
}

但这有时会给我带来错误

but this is giving me error some times

无法读取 null 的属性 'top'

我不太擅长 JavaScript

I am not so good with JavaScript

有人可以帮忙解决这个问题吗?

Can any one help with this issue?

我发现了问题.


这个 snapToAnchor 函数在一个对话框模型中,所以当我第二次点击这个函数时,没有生成列表,这就是为什么我有空值,所以我做的是在触发这个函数之前,我重新创建了模态,然后进入函数,现在没有 null 的作用域.

I found the Problem.


This snapToAnchor function is in a dialog model, so second time when i hit this function, there is not list generated, that's why i have null value, so what i did is before firing this function, i recreate the modal and then step in to the function, now no scope of null.

推荐答案

锚变量不包含您站点的有效选择器.对此调用 offset 将返回 null.

The anchor variable does not contain a valid selector for you site. Calling offset on this will return null.

示例

var a = $('#non-existing-id'); //returns empty object
var b = a.offset(); // returns null
b.top; //throws a TypeError exception

您可以通过在第 3 行插入 alert(anchor) 来简单地调试您的程序.这将显示变量的内容.

You can simply debug your program by inserting alert(anchor) on line 3. This will show you the contents of the variable.

这篇关于JavaScript - 无法读取 null 的属性“top"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆