简体   繁体   中英

jQuery click event on button added through datatable jquery plugin

I am creating a table using the datatable plugin. Have added buttons to last column of the table. Issue: The button's on click is not triggered.

Javascript where table is created.

<script>
  $(document).ready(function() {
    $('#tagtbl').DataTable( {
        "paging": false,
        "info": false,
        "searching": false,
        "ajax": "../api/clienttagtbl.php?off=OFF002",
        "rowId": "id",
        "columns": [
            { "data": "tagname" },
            { "data": null, "defaultContent": '<button id="tagdelete" type="button" class="btn btn-danger btn-sm" >X</button>' }
        ]
    } );
  } );
</script>

Javascript where On click is called

<script>
$(document).ready(function() {
  $('#tagdelete').click( function(){
    console.log("hi"); // <<---This is not working
  });
  $('#tagtbl').click( function(){
    console.log("hi2");  //<<---This is working
  });
});
</script>

HTML

    <table id="tagtbl" class="table table-sm" >
      <thead>
        <tr>
          <th>Tag Name</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <th>Tag Name</th>
          <th></th>
        </tr>
      </tbody>
    </table>

HTML表格

Try this

 $('#tagtbl').on('click','.tagdelete' function(){
    console.log("hi");
  });

i recommend you use a class for all the buttons instead of using id.

you need to add the button click in datatable drawCallback function

$('#example').dataTable( {
    "drawCallback": function( settings ) {
       $('#tagdelete').click( function(){
    console.log("hi");
  });
  $('#tagtbl').click( function(){
    console.log("hi2");
  });
    }
} );

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