添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I had a table within my MVC 5 View which repeated out rows of data. Each row had a button attached to it which when clicked upon would pass the data-id into a hidden text box using JQuery

MVC View

@foreach (var item Model.MyList) {
//<tr> etc
  <button class="btn btn-danger btn-xs" id="btnDelete" data-toggle="modal" data-target="#myModal" data-id="@item.ID"> Delete </button>

JQuery

$(document).ready(function () {
    //Everytime we press delete in the table row
    $('.btn.btn-danger').click(function () {
        //Update the text box with delete id so our model knows which one to delete
        $('#item-to-delete').val(id);

I then decided to replace my table with https://datatables.net/ for several reasons. The problem now, is that when the user clicks the Delete button inside the Datatable, my JQuery click function is no longer called and therefore the delete ID is not passed into my hidden textbox.

This is my DataTable script

<script>
    $(document).ready(function () {
        $('#dataTables-example').dataTable({  
            "bServerSide": true,  
            "sAjaxSource": "/MyController/GetAjaxData",
            "bProcessing": true,
            "bJQueryUI": true,
            "aoColumns": [
                      { "sName": "ID", "visible": false },
                      null, //FullName
                      null, //Email
                      null, //LastLoginDate
                          "mData": null,
                          "mRender": function (data, type, full) {
                              return "<button class='btn btn-danger btn-xs' id='btnDelete' data-toggle='modal' data-target='#myModal' data-id='"+ full[0] +"'>Delete</button>";
</script>

Can anyone please see why this is happening or advise me on how to fix the problem?

Thanks alot.

Instead of $('.btn.btn-danger').click(function ()...

Try use .on to bind the event to a later created dom element.

Many people have already asked this question. See jQuery function not binding to newly added dom elements

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.