简体   繁体   English

表格中的删除按钮,jQuery

[英]Delete button in table, jQuery

I wrote the code, using JS and jQuery. 我使用JS和jQuery编写了代码。 The code adds new rows to my table. 代码将新行添加到表中。 Every row contains the delete button and it do not work. 每行都包含删除按钮,但它不起作用。 I'm going to implement also edit button. 我要实现还编辑按钮。

My table: 我的桌子:

<div class="row">
   <div class="col-md-12">
      <table class="table table-striped" id = "my-table">
       <thead>
        <tr>
            <th>Date</th>
            <th>Example</th>

        </tr>
          </thead>
          <tbody>



          </tbody>

        </table>

   </div>
   </div>
  </div>

JS code: JS代码:

$(document).ready(function(){
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd='0'+dd
} 

if(mm<10) {
mm='0'+mm
} 
today = mm+'/'+dd+'/'+yyyy;
//var counter = 1;


$('button#sending_button').click(function(){
    var text = $('textarea#mytextarea').val();
    $('#my-table').append('<tr><td>'+today+'</td><td>'+text+'</td><td><button type="button" id="delete-button"  class="btn btn-danger">Usuń</button></td></tr>');
    $('textarea#mytextarea').val('');
    //counter++;

});

$('#my-table').on('click', 'button.btn btn-danger', function() {
    $(this).parents('tr').remove();  

});

}); });

I don't know what more I should explain about this problem. 我不知道该问题我还需要解释什么。

Your problem is here: 您的问题在这里:

$('#my-table').on('click', 'button.btn btn-danger', function() {

It should be button.btn.btn-danger . 它应该是button.btn.btn-danger

Some random suggestions: 一些随机的建议:

  • Don't repeat the id of each button (" delete-button "): id's should be unique 不要重复每个按钮的ID(“ delete-button ”):ID应该是唯一的
  • Use a semantically meaningful class instead ( delete button would also be good) 请改用语义上有意义的类( delete button也可以)
  • Use said class when defining the delegate event listener, instead of button.btn.btn-danger (which is too bound to the DOM and its style definition) 定义委托事件侦听器时,请使用上述类,而不要使用button.btn.btn-danger (它太与DOM及其样式定义绑定了)
  • Use parent instead of parents to avoid surprises. 使用parent而不是parents来避免意外。 They're two different methods with different goals 它们是目标不同的两种不同方法
  • Event better, use closest . 事件效果更好,请使用closest

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

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