简体   繁体   中英

JQUERY: Keep Class in last appended element and remove from all other newly added elements in a TABLE

I have a table & in each TR if I click the icon a new TR is appended to the end. TR also has a row_seperator class. I want this row_seperator to be removed from previous all newly appended rows but remain in the last appended row TR.

$(this).closest('tr').removeClass("row_seperator") ;      
$('.new_row').removeClass('row_seperator').removeClass('new_row');
$('<tr class="row_seperator new_row"><td colspan="8">new td</td></tr>').insertAfter($(this).closest('tr'));

As shown below in the image. I want these two crossed lines to disappear & the last line to remain. So that each section has a line to separate it from other sections.

在此处输入图片说明

    <table class="authors-list">
       <tr class="row_seperator">
          <td>Column 1</td>
          <td>Column 2</td>
       </tr>
       <tr class="row_seperator">
          <td><input type="text" name="first_name" /></td>
          <td><input type="text" name="last_name" /></td>
       </tr>
    </table>
    <a href="#" title="" class="add-author">Add</a>


// Jquery Code


        var counter = 1;
        $('a.add-author').click(function(event){
            event.preventDefault();
            counter++;
            $(".authors-list tr").addClass("row_seperator");
            var newRow = jQuery('<tr><td><input type="text" name="first_name' +
                counter + '"/></td><td><input type="text" name="last_name' +
                counter + '"/></td></tr>');
            $('table.authors-list').append(newRow);
        });

Working Fiddle http://jsfiddle.net/yUfhL/1097/

I suppose this refers to the icon clicked. In which case $(this).closest('tr') will be always the TR with "Section-A" (or -B, -C, depending on which icon was clicked). And this means that each new TR will be inserted above the previous TRs, so it will be always the first new TR that must have the row_separator class.

If all what I supposed is correct, I would simply check if $(this).closest('tr').hasClass('row_separator') , and if so, I would call removeClass on it and addClass on the new element (or include the class in the string as you did). If not, I would do neither.

If - on the other hand - you would like to insert new TRs after the previous new TRs , you can add some distinctive class to the TRs having the icon and call $(this).closest('tr').nextUntil('distinctive_class').last().after(newTr);

Also be aware that if you have added some new TRs after Section-A, B and C and call $('.new_row').removeClass('new_row'); it will remove class from every .new_row not only from the ones after the TR of the icon clicked.

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