使用dataTables和Bootstrap模式

fil*_*tea 2 datatable jquery datatables twitter-bootstrap

我有一个包含200多条记录的dataTable,其中每一行都有按钮来删除该记录,当按下按钮时,会弹出一个来自Bootstrap的模态.

问题是,当我使用dataTable中的分页选项更改"页面"时,模式内的信息不会使用相应的ID进行更新.当我点击第一页的任何一行时,它可以正常工作,但是当我更改页面时,信息会被我从第一页按下的最后一个ID卡住.

有任何想法吗?

Mi代码看起来像这样:

<table class="table table-bordered table-hover tablewithtooltip" id="dataTable">
  <thead>
    ...
  </thead>

  <tbody>
    <tr>
      <td>
        <a href="#myModal" role="button" class="btn delete-smt-btn" data-toggle="modal" id="111">Delete Row</a>
      </td>
      <td>Some info</td>
    </tr>

    <tr>
      <td>
        <a href="#myModal" role="button" class="btn delete-smt-btn" data-toggle="modal" id="112">Delete Row</a>
      </td>
      <td>Some info</td>
    </tr>

    ...

  </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

这是我的jQuery:

$('body').on('hidden', '#myModal', function () {
  $(this).removeData('modal');
});

var table = $('#dataTable').dataTable({
    "sDom": "<'row'<'span6'l><'span6'f>r>t<'row'<'span6'i><'span6'p>>",
    "sPaginationType": "bootstrap",
    "aaSorting": [[ 3, "asc" ]],
    "oLanguage": {
        "sLengthMenu": "Mostrar _MENU_ registros por página"
    }
});

$('.delete-smt-btn').on('click', function(e){
    id = e.currentTarget.id;
    url = "mypage.com/something?p_something=" + id;

    $('#myModal').modal({
        remote : url
    });
    $('#myModal').removeData();
});

// I have some tooltips on my table, and I was having kind of the same issue when
// I changed pages with dataTable, the tooltip wasnt showing and I solved it with
// this but I cant make it work with modal.

    table.$('[rel="tooltip"], [data-toggle=tooltip]').tooltip({
      html: true
    }).click(function(e) {e.preventDefault();});
Run Code Online (Sandbox Code Playgroud)

cfs*_*cfs 5

尝试将委派的事件侦听器附加到表中.当表最初呈现时,事件处理程序将附加到您的按钮,但是当您翻阅表时,这些按钮将被销毁并创建新按钮.这些新按钮是在分配处理程序后创建的,因此它们不会侦听click事件.

对于这样的情况,使用委托事件侦听器也是最佳做法,在这种情况下,您有许多元素在同一事件上触发相同的功能.委托事件只分配一个处理程序,否则您将为每个元素分配一个处理程序,这将影响内存/性能

$('#dataTable').on('click', '.delete-smt-btn', function(e){
    id = e.currentTarget.id;
    url = "mypage.com/something?p_something=" + id;

    $('#myModal').modal({
        remote : url
    });
    $('#myModal').removeData();
});
Run Code Online (Sandbox Code Playgroud)