英文:
How do I create a jquery function so that a clicked button will scroll to the next date
问题 {#heading}
我有一个带有类名 'next' 的触发按钮,并编写了以下 jQuery 函数:
$(document).ready(function () {
$(".next").click(function (e) {
e.preventDefault();
console.log('got here');
var currentDate = new Date();
console.log(currentDate);
var dateElements = $(".date");
var nextDateElement = null;
dateElements.each(function () {
var date = new Date($(this).text());
if (date > currentDate) {
nextDateElement = $(this);
return false; // 退出循环
}
});
if (nextDateElement) {
$('html, body').animate({
scrollTop: nextDateElement.offset().top
}, 'slow');
}
});
});
但是它无法正常工作,甚至无法显示控制台日志。我可能做错了什么? 英文:
I have a trigger button with a class of 'next'and I have coded a jquery function as follows:
$(document).ready(function () {
$(".next").click(function (e) {
e.preventDefault();
console.log('got here');
var currentDate = new Date();
console.log(currentDate);
var dateElements = $(".date");
var nextDateElement = null;
dateElements.each(function () {
var date = new Date($(this).text());
if (date > currentDate) {
nextDateElement = $(this);
return false; // Exit the loop
}
});
if (nextDateElement) {
$('html, body').animate({
scrollTop: nextDateElement.offset().top
}, 'slow');
}
});
`});
`
but I can't get it to work - or even display the console log. What might I be doing wrong?
答案1 {#1}
得分: 1
需要添加一些额外的填充吗?"Offset" 定义了元素的顶部位置。尝试这样做:
scrollTop: nextDateElement.offset().top + 100
其他尝试的事项:
-
确认你的逻辑是否正确。使用控制台记录所有日期,以确保它们符合你的预期。
-
尝试不使用动画效果:
$('html').scrollTop(nextDateElement.offset());
英文:
Do you need to add some additional padding? Offset defines the top of the element. Try this:
scrollTop: nextDateElement.offset().top + 100
Other things to try:
-
Confirm your logic is correct. console log all the dates to make sure they're what you expect.
-
Try it without animate
$('html').scrollTop( nextDateElement.offset() );