繁体   English   中英

删除 <tr> 从表与jQuery

[英]Removing <tr> from table with jQuery

我有2个表,每行都有自己的删除自身按钮:

 <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>

还有两个简单的JQuery代码,用于每个表,可用于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();
    });

当我单击第一个表中的“ X”按钮时,它工作正常。 第一个表中的行已删除...但是,当我单击第二个表中的“ X”按钮时,它将同时从第二个表和第一个表中删除行。 从两个表中删除具有相同编号的同一行。为什么?

首先,具有多个具有相同id元素是无效的HTML。

但是,您可以使用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函数

不知道您需要做这么多的编码。

您可以通过:

 $(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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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