我要做的就是,当我按下类next_btn
的按钮时,从第一个div滚动到第二个div(都具有“ question”类)。我觉得我的jQuery是正确的,但是,当我单击时什么也没发生。
注意:之后,我将添加更多问题,因此我不想为每个问题和每个按钮都使用id。
控制台错误:
未捕获的TypeError:无法读取未定义的属性“ top”
$(".next_btn").click(function() {
$('html, body').animate({
scrollTop: $(this).parents().next('.question').offset().top
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="question">
<div class="row header">
<div class="col-sm-12 logo">
<img src="q.png" height="350px;">
</div>
</div>
<div class="col-sm-12 buttons" style="left:0px; text-align:center;">
<button class="btn next_btn">NEXT</button><br>
</div>
</div>
<div class="question">
<div class="row header">
<div class="col-sm-12 logo">
<img src="q.png" height="150px;">
</div>
</div>
<div class="row content">
<div class="col-sm-12 buttons" style="left:0px; text-align:center;">
<button class="btn next_btn">NEXT</button><br>
</div>
</div>
</div>
答案 0 :(得分:0)
单击最后一个按钮时会收到此错误,因为他的旁边没有.question
,所以$(this).parents().next('.question')
返回undefined
,您可以添加代码段显示之类的条件
//Get the next question
var next_question = $(this).parents().next('.question');
// Check if the question exist them animate
if (next_question.length) {
$('html, body').animate({
scrollTop: next_question.offset().top
}, 1000);
}
$(".next_btn").click(function() {
var next_question = $(this).parents().next('.question');
if (next_question.length) {
$('html, body').animate({
scrollTop: next_question.offset().top
}, 1000);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<br><br><br><br><br><br>
<div class="question">
<div class="row header">
<div class="col-sm-12 logo">
<img src="q.png" height="350px;">
</div>
</div>
<div class="col-sm-12 buttons" style="left:0px; text-align:center;">
<button class="btn next_btn">NEXT</button><br>
</div>
</div>
<div class="question">
<div class="row header">
<div class="col-sm-12 logo">
<img src="q.png" height="150px;">
</div>
</div>
<div class="row content">
<div class="col-sm-12 buttons" style="left:0px; text-align:center;">
<button class="btn next_btn">NEXT</button><br>
</div>
</div>
</div>
<div class="question">
<div class="row header">
<div class="col-sm-12 logo">
<img src="q.png" height="150px;">
</div>
</div>
<div class="row content">
<div class="col-sm-12 buttons" style="left:0px; text-align:center;">
<button class="btn next_btn">NEXT</button><br>
</div>
</div>
</div>
<div class="question">
<div class="row header">
<div class="col-sm-12 logo">
<img src="q.png" height="150px;">
</div>
</div>
<div class="row content">
<div class="col-sm-12 buttons" style="left:0px; text-align:center;">
<button class="btn next_btn">NEXT</button><br>
</div>
</div>
</div>
<br><br><br><br><br><br><br><br><br>