What I want is to be able to produce something like this one...
But why if else in the jquery that I executed doesn't work as expected as in the picture?
This in my html code
<div>
<div class="card1 active">
<p>CARD 1</p>
<button class="btn-back">BACK</button>
<button class="btn-next">NEXT</button>
</div>
<div class="card2">
<p>CARD 2</p>
<button class="btn-back">BACK</button>
<button class="btn-next">NEXT</button>
</div>
<div class="card3">
<p>CARD 3</p>
<button class="btn-back">BACK</button>
<button class="btn-next">NEXT</button>
</div>
<div class="card4">
<p>CARD 4</p>
<button class="btn-back">BACK</button>
<button class="btn-next">NEXT</button>
</div>
</div>
and this my css(less) code
div {
padding: 10px;
.card1,.card2,.card3,.card4 {
display: none;
border-radius: 10px;
margin-bottom: 10px;
background: #777;
}
.active {
display: block;
}
}
jQuery
$(document).ready(() => {
$(".btn-next").click(() => {
if($(".card1 p").html() === "CARD 1") {
$(".card2").addClass("active");
} else if($(".card2 p").html() === "CARD 2") {
$(".card3").addClass("active");
} else if($(".card3 p").html() === "CARD 3") {
$(".card4").addClass("active");
}
});
});
The main issue is your click listener - you are using an if-else block which will only run the if
statement for $(".card1 p").html() === "CARD 1"
is always true
.
You can fixed it by rearranging the if-else
statements (put the $(".card1 p").html() === "CARD 1"
in the else
block; $(".card2 p").html() === "CARD 2"
to the second else-if
block, etc).
You can also ease the checking by just using the active
class and the hasClass
method of jquery
. Instead of $(".card1 p").html() === "CARD 1"
, you can go with $(".card1").hasClass('active')
Wrapping it up, rather than using if-else statements, I suggest you use another method for handling the button clicks. The following is my own implementation
$(document).ready(() => { $(".btn-next").click(e => $(e.target).parent().next().addClass('active')); });
div { padding: 10px; }.card1,.card2,.card3,.card4 { display: none; border-radius: 10px; margin-bottom: 10px; background: #777; }.active { display: block; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <div class="card1 active"> <p>CARD 1</p> <button class="btn-back">BACK</button> <button class="btn-next">NEXT</button> </div> <div class="card2"> <p>CARD 2</p> <button class="btn-back">BACK</button> <button class="btn-next">NEXT</button> </div> <div class="card3"> <p>CARD 3</p> <button class="btn-back">BACK</button> <button class="btn-next">NEXT</button> </div> <div class="card4"> <p>CARD 4</p> <button class="btn-back">BACK</button> <button class="btn-next">NEXT</button> </div> </div>
I utilized some jquery traversing methods which are parent()
and next()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.