简体   繁体   中英

traversing dom in jquery find previous instance of class

I have the following repeating pattern of tables and buttons

----------------------
table 1 .inventory class
----------------------
[button 1 .add-row]

----------------------
table 2 .inventory class
----------------------
[button 2 .add-row]

----------------------
table 3 .inventory class
----------------------
[button 3 .add-row]

now when i click button 1,2,3 i want to traverse to table 1,2,3 respectively (the previous table) and display an extra row o nthe table(already created, just hidden), I tried this but all the buttons only effect the first table first and once all those rows are displayed it then starts displaying on the next table etc etc, i know the answer is probably obvious.. heres my code:

$(document).ready(function(){
    $('.additional-item-row').hide();
    $('.add-item').click(function(){
        $(this).prevAll(".inventory .additional-item-row:hidden:first").show();
    });
});

Try this:

$(document).ready(function(){
    $('.additional-item-row').hide();
    $('.add-item').click(function(){
        $(this).prev("table").children(".inventory .additional-item-row:hidden:first").show();
    });
});

好吧,我设法解决它:

$(this).prevAll(".inventory:first").find(".additional-item-row:hidden:first").show();

Assumption: the index of the button in the set of buttons matches the index of the table row in the set of table rows.

$(function() {
    $("button.add-item").click(function() {
        var index = $("button.add-item").index(this);
        $("tr.additional-item-row:eq(" + index + ")").show();
    });
});

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