I am trying to find the next div after an input button and toggle it.
What am I doing wrong?
JS:
$(".showNextExperience").click(function() {
$(".experience").show();
});
HTML:
<input class="showNextExperience" >
<div class="experience">Experience 1</div>
<input class="showNextExperience">
<div class="experience">Experience 2</div>
<input class="showNextExperience">
<div class="experience">Experience 3</div>
<input class="showNextExperience" >
<div class="experience">Experience 4</div>
Okay, this DOES NOT work ---
$(".showExperience").click(function() {
$(this).next(".experience").toggle();
});
<table class="data">
<tr class="tableHead">
<td></td>
<td width="50" align开发者_StackOverflow中文版="right"><input type="button" class="showExperience" value="show"></td>
</tr>
</table>
<div class="experience">2</div>
When I move the input button just above the DIV it works just fine.
$(".showExperience").click(function() {
$(this).next(".experience").toggle();
});
<input type="button" class="showExperience" value="show">
<div class="experience">2</div>
Can you explain that?
Simply:
$(".showNextExperience").click(function() {
$(this).next(".experience").toggle();
});
See:
- http://api.jquery.com/toggle/
- http://api.jquery.com/next/
$(".showNextExperience").click(function() {
$(this).next().show();
});
Try this
$(".showNextExperience").click(function() {
$(this).next("div.experience").toggle();
});
$(this).siblingings().eq(0)
should to do it.
Assuming you have elements between triggering input and manipulated div:
<input class="showNextExperience" >
<p>Hello, new line</p>
<div class="experience">Experience 1</div>
<input class="showNextExperience">
<p>Some text</p>
<div>And an info block</div>
<div class="experience">Experience 2</div>
Then you have to use nextAll
to search not only for the very next element but through the whole DOM, which is probably simpler coding than using next().find()
:
$(".showNextExperience").click(function() {
$(this).nextAll(".experience").toggle();
});
精彩评论