#jquery #undefined
#jquery #не определено
Вопрос:
Привет, я получил это сообщение здесь: Неперехваченная ошибка типа: не удается прочитать свойство ‘top’ неопределенного
'scrollTop': $target.offset().top - 60
Блок кода:
$('.btn-circle-cover').on('click',function (e) {
e.preventDefault();
var target = this.hash,
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top - 60
}, 2200, 'swing', function () {
window.location.hash = target;
});
});
Комментарии:
1.
$(this.hash)
недопустимый селектор jQuery. Вы имеете в виду$(this)
?
Ответ №1:
this.hash
недопустимо, потому this
что будет представлять <button>
то, которое не будет иметь href
. Вместо этого перейдите к родительскому элементу, который имеет href
атрибут using .parentNode
и use .hash
, чтобы получить хэш href
.
Пример:
$('.btn-circle-cover').on('click', function(e) {
e.preventDefault();
var target = this,
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top - 60
}, 2200, 'swing', function() {
console.log('hash is: ', e.currentTarget.parentNode.hash)
window.location.hash = e.currentTarget.parentNode.hash;
});
});
body {
height: 4000px;
}
button {
margin-top: 3000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Scroll Down</p>
<a href="#hdsf">
<button class="btn-circle-cover">Click here</button>
</a>