简体   繁体   中英

Removing <tr> from table with jQuery

I have 2 tables and every row has own button for deleting itself :

 <table class="table" id="Offers">
       <tr id="row1">
        <td><button type="button" id=1 class="removeOffer">X</button</td>
       </tr>   
 </table>

 <table class="table" id="OffersHistory">
       <tr class="History1">
        <td><button type="button" id=1 class="removeOfferHistory">X</button</td>
      </tr>   
 </table>

And two simple JQuery code, for every table , serving for remove :

   $(document).on('click', '.removeOffer', function(){
        var button_id = $(this).attr("id");
        $('#row'+button_id).remove();
   });

    $(document).on('click', '.removeOfferHistory', function(){
        var button_id = $(this).attr("id");
        $('.History'+button_id).remove();
    });

When i click on "X" button in the first table, it works fine. Row from first table is removed... But when i click on "X" button from second table, it removes row from second and first at the same time. Same row with same number from both tables are removed.. Why?

Firstly, it's invalid HTML to have multiple elements with the same id .

But, you could simplify your code massively by using the power of jQuery...

 $(function(){ $("button").on("click", function(e) { e.preventDefault(); $(this).closest("tr").remove(); }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr> <td>First Row</td> <td><button>X</button></td> </tr> <tr> <td>Second Row</td> <td><button>X</button></td> </tr> </table> 

两个按钮的ID为1,更改ID或调用按钮内的javascript函数

Not sure you need to do this much coding.

You can simply do it by : -

 $(document).ready(function() { $('button').click(function() { $(this).remove(); }); }); 
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Remove button</title> </head> <body> <script src="https://code.jquery.com/jquery-3.1.0.js"></script> <button class="first" value="button1">button1</button> <button class="first" value="button1">button2</button> </body> </html> 

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