How to get immediately following siblings up to next unmatched selector
-
06-07-2021 - |
質問
I have the following table
<table id="table">
<tr><td>Item</td></tr>
<tr class="hide"><td>Hidden Item</td></tr>
<tr class="hide"><td>Hidden Item</td></tr>
<tr class="hide"><td>Hidden Item</td></tr>
<tr><td>Item</td></tr>
<tr class="hide"><td>Hidden Item</td></tr>
<tr class="hide"><td>Hidden Item</td></tr>
<tr><td>Item</td></tr>
<tr class="hide"><td>Hidden Item</td></tr>
<tr class="hide"><td>Hidden Item</td></tr>
<tr class="hide"><td>Hidden Item</td></tr>
<tr class="hide"><td>Hidden Item</td></tr>
<tr><td>Item</td></tr>
</table>
on clicking on a visible row, i want to show all the immediately following hidden rows up to the next visible row. The number of hidden rows is not fixed. How can I select immediately following rows up to a specific element?
解決
//Add a class to your visible rows if possible to replace the next selector
$('tr:visible').click(function() {
$('.hide').hide();
$(this).nextUntil(':visible').fadeIn();
});
Adding a show
class to the visible rows, you can add a simple toggle effect to it:
$('.show').click(function() {
$(this).nextUntil('.show').not('.show').fadeToggle();
});
A slightly more elaborated version which toggles the clicked rows' section and hides the rows which were previously open:
$('.show').click(function() {
$('.hide').not(
$(this).nextUntil('.show').not('.show').fadeToggle()
).hide();
});
他のヒント
You can use .nextUntil() - replacing $('tr:first') with your element -
$('tr:first').nextUntil('tr:not(.hide)').show()
// from first tr until next one that doesn't have class=hide
Though I would probably use toggle() to hide/show the following elements - I'm not sure what your goal is though so you can do what you want afterwards
$('.hide').hide();
$('tr:not(.hide)').click(function(){
$(this).nextUntil('tr:not(.hide)').toggle();
});
I think this is what you are looking for: jQuery .nextUntil()
use nextUntil
$('tr').click(function(){
$(this).nextUntil(':not("tr.hide")').show();
});
find jsfiddle http://jsfiddle.net/K5QcA/
for reference http://api.jquery.com/nextUntil/