首页 > 解决方案 > Bootstrap 可点击可排序 - 排序后无法点击

问题描述

我正在使用 Bootstrap 4.2.1 和 bootstrap-table 1.13.3 来创建一个每行可排序和可点击的表。在对表格进行排序之前,每一行都是可点击的。

排序后谷歌工具显示 TR 点击事件处理程序已被删除。

点击处理程序被添加到 onload 事件处理程序中,如下所示。我应该怎么做才能防止点击事件被删除或在排序操作后恢复点击事件?

function onLoaded(){
   $(function(){
      $('.table tr[data-href]').each(function(){
         $(this).click(function(){
         document.location = $(this).attr('data-href');
        });
      })
    });
}
tr.clickable-row {
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.bundle.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.13.3/bootstrap-table.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.13.3/bootstrap-table.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet"/>

<body onload="onLoaded()">
  <wrapper class="d-flex flex-column">
      <main class="container">
          <div class="table-responsive-sm">
              <table data-toggle="table" data-sortable="true" class="table table-sm table-striped table-bordered table-hover">
                  <thead class="thead-light">
                      <tr>
                          <th data-sortable="true" scope="col">
                              For
                          </th>
                          <th data-sortable="true" scope="col">
                              Name
                          </th>
                      </tr>
                  </thead>
                  <tbody>
                      <tr class="clickable-row" data-href="ZZZZ.html?YYYY=32">
                          <td>Paul Read</td>
                          <td>23/05/2018 13:11</td>
                      </tr>
                      <tr class="clickable-row" data-href="ZZZZ.html?YYYY=31">
                          <td>Paul Read</td>
                          <td>23/05/2018 13:09</td>
                      </tr>
                  </tbody>
              </table>
          </div>
      </main>
  </wrapper>
</body>

非常感谢保罗

标签: twitter-bootstrapjquery-ui-sortablebootstrap-tableclickable

解决方案


我已将您的代码编辑到这个小提琴中:http: //jsfiddle.net/eitanmg/frmLy3q8/12/

关键是使用内置onClickRow事件,所以在对表格进行排序/搜索/过滤后仍然保留该功能。

进行的其他编辑:

我已经删除了onload="onLoaded()"in body 标签并onLoaded()完全删除了该功能。我已添加id="table"到 table 标记,因此可以从 javascript 代码中引用它。而不是onLoaded()函数,我将onClickRow事件用作:

$('#table').on('click-row.bs.table', function (row, $element, field) {
    alert("you are about to navigate to the following url: " + $element._data.href)
    document.location = $element._data.href;
});

推荐阅读