프로그래밍/html,css,js
js Cannot read properties of undefined xxx 해결
◎◇
2023. 5. 26. 11:41
오류코드
Uncaught TypeError: Cannot read properties of undefined (reading 'top')
첫번째 해결 방안 (실패)
if ('top' in $(el_target).offset()) {
// 'top' 속성이 존재하는 경우에 대한 처리
// ...
} else {
// 'top' 속성이 존재하지 않는 경우에 대한 처리
// ...
}
실패 이유 :
1) 오류코드 발생
2) Uncaught TypeError: Cannot use 'in' operator to search for 'top' in undefined
3) $(el_target).offset() 값 자체가 undefined이기때문에
두번째 해결 방안 (성공)
var offset = $(el_target).offset();
if (offset && 'top' in offset) {
// 'top' 속성이 존재하는 경우에 대한 처리
// ...
} else {
// 'top' 속성이 존재하지 않거나 offset이 유효하지 않은 경우에 대한 처리
// ...
}