JavaScript - 无法读取 null 的属性“top”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7933582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:47:43  来源:igfitidea点击:

JavaScript - Cannot read property 'top' of null

javascriptnullpointerexception

提问by HaBo

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

但这有时给我错误

saying Cannot read property 'top' of null

无法读取 null 的属性“top”

I am not so good with JavaScript

我不太擅长 JavaScript

Can any one help with this issue?

任何人都可以帮助解决这个问题吗?

I found the Problem.

我发现了问题。



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

采纳答案by topek

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

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

Example

例子

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

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

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

回答by Scherbius.com

if anchorhas id of the DOM element - then correct way to use it with jQuery:

如果具有 DOM 元素的 id - 那么在 jQuery 中使用它的正确方法:

$('#' + anchor).offset()

otherwise you'll get a null (and error).

否则你会得到一个空值(和错误)。

回答by Tim Joyce

$(anchor).offset().top

will usually output a string not a number... something like 100px. you need to extract the number from the string.

通常会输出一个字符串而不是数字......比如100px。您需要从字符串中提取数字。

var topoffset = $(anchor).offset().top;
topoffset = topoffset.split('px', 1);