so I discover that the for loop (i++) method only works in some cases in my projects and this is one of the cases that it does NOT work. I never knew why it doesn't work and still haven't found the answer.
I hope people around could help me out since this is starting to bring me problems. No matter if we do it with jQuery or with vanilla JS, as long as I could get through this problem.
I did a very small jFiddle, the real codes are larger and with ajax calls here and there but it is pretty much the same, I usually need to use the following (js script) INSIDE the ajax success, but I use something like "closest.find('.example)" instead, and for some reason I want to stop using that method.
https://jsfiddle.net/un12bjq3/1/
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
button {
padding: 10px 10px 10px 10px;
background-color: midnightblue;
border: 0;
border-radius: 10px;
color: white;
font-size: 22px;
cursor: pointer;
}
.container,
.container_ {
display: table;
font-size: 20px;
color: black;
border: 1px solid black;
padding: 10px 10px 10px 10px;
margin-top: 10px;
}
.border_div {
float: left;
display: table;
padding: 10px 30px 10px 30px;
border-radius: 10px;
border: 1px solid black;
margin-right: 10px;
margin-left: 10px;
margin-top: 10px;
}
</style>
</head>
<body>
<div class="border_div">
<h2>
With eq(i)..<br>Not working
</h2>
<button class="btn">
Btn 1
</button>
<div class="container">
Container 1
</div>
<br>
<br>
<button class="btn">
Btn 2
</button>
<div class="container">
Container 2
</div>
</div>
<div class="border_div">
<h2>
Without eq(i)<br>It only works with<br>a real number
</h2>
<button class="btn_">
Btn 1
</button>
<div class="container_">
Container 1
</div>
<br>
<br>
<button class="btn_">
Btn 2
</button>
<div class="container_">
Container 2
</div>
</div>
<script>
for (var i = 0; i < 5; i++) {
$('.btn').eq(i).click(function() {
$('.container').eq(i).toggle();
});
}
// How can I auto detect the eq() index ?
// This is a working example with eq(0)
$('.btn_').eq(0).click(function() {
$('.container_').eq(0).toggle();
});
</script>
</body>
</html>
Thanks a lot!