简体   繁体   中英

Jquery : To find the closest tr class

Below is my structure

-Clicking on flight_itinerary class should open flight_summary class html.

<table>
    <tr>
        <td>
            <table>
                <tr>
                    <td><a class="flight_itinerary">Flight Itinerary</a> </td> 
                </tr>   
            </table> 
        </td>
    </tr>
    <tr class="flight_summary" style="display:none;">
        <td>
            <table>
                <tr>
                    <td></td> 
                </tr>   
            </table> 
        </td>           
    </tr>
</table>
  • This is my script which i tried to open tr tag

    $(document).on('click', '.flight_itinerary', function(){
            $(this).closest("tr").find('.flight_summary').toggle();
});

.find() looks for a descendant matching the selector. When you go to the closest tr from .flight_itinerary , .flight_summary is not one if its descendants.

To get to .flight_summary from .flight_itinerary , you have to go up to the 2nd tr , then go to the next tr after that. You don't need to use .find there, because that tr is .flight_summary .

 $(document).on('click', '.flight_itinerary', function() { $(this).parents("tr").eq(1).next().toggle(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr><td> <table> <tr> <td><a class="flight_itinerary">Flight Itinerary</a> </td> <tr> </table> </td></tr> <tr class="flight_summary" style="display:none;"> <td><table> <tr> <td>Flight Summary</td> <tr> </table> </td></tr> </table> 

It's a bit of an awkward way of getting there, but the tables within tables doesn't help

$(document).on('click', '.flight_itinerary', function(){
    $(this).parent('tr').parent('table').parent('tr').parent('table').find('.flight_summary').toggle();
});

To make it a little cleaner, you could add a class to the main table (the big one housing all the rows and internal tables), and then do this;

// Assuming we added a class of 'main' to the outermost table

$(document).on('click', '.flight_itinerary', function(){
    $(this).parents('table.main').find('.flight_summary').toggle();
});

That would find the main table, then search for it's child row with the class of flight-summary

If you wanted the first matched instance of .flight_summary , then this would do that

$(document).on('click', '.flight_itinerary', function(){
    $(this).parents('table.main').find('.flight_summary').eq(0).toggle();
});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM