JavaScript - Cannot read property 'top' of

2019-07-23 15:43发布

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

I am not so good with JavaScript

Can any one help with this issue?

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.

3条回答
成全新的幸福
2楼-- · 2019-07-23 16:37

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

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

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

查看更多
迷人小祖宗
3楼-- · 2019-07-23 16:43

The anchor variable does not contain a valid selector for you site. Calling offset on this will return 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.

查看更多
forever°为你锁心
4楼-- · 2019-07-23 16:44
$(anchor).offset().top

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

var topoffset = $(anchor).offset().top;
topoffset = topoffset.split('px', 1);
查看更多
登录 后发表回答