首页 > 解决方案 > 如何阻止 DataTable 在单击动态添加到标题的子元素时进行排序?

问题描述

这个问题听起来已经有答案了。

一直在寻找答案,我一直在event.stopPropagation()回复。但是为什么它在这个小提琴上不起作用?我错过了什么吗?

$(document).ready(function(){
  $('#test-table').DataTable()

  $('#test-table thead tr th').each(function(i, e) {
    $(this).append('<button id="test-button" style="margin-left: 5px; margin-right: 5px;">Test Button</button>')
  })

  $('body').on('click', '#test-button', function(e) {
    alert('test')
    e.stopPropagation()
  })

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" rel="stylesheet"/>

<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>


<table id="test-table" class="table table-striped table-bordered">
  <thead>
    <th>Name</th>
    <th>Description</th>
  </thead>
  <tbody>
    <tr>
      <td>a</td>
      <td>a</td>
    </tr>
    <tr>
      <td>b</td>
      <td>b</td>
    </tr>
  </tbody>
</table>

标签: javascriptjquerydatatablesonclick

解决方案


看看JSFiddle:https ://jsfiddle.net/0fyxws79/2/

您只需要在应用点击事件之前更改选择器。a) 较早的按钮被选择为关于 body 元素 & on body 没有任何进一步的事件,这就是为什么您无法确定 stopPropagation 是否正常工作的原因。

b) 现在可以找到与附加了排序事件的表头相关的按钮。每当我们点击表头内的按钮时,它就会停止相应的选择器事件。

01)小提琴:这里的点击事件附加到HTML正文只是为了让您知道&您的问题代码在这里工作但以不同的方式工作。 https://jsfiddle.net/0fyxws79/1/

02)小提琴:这里的排序事件已经出现在表头上,这是我们需要防止点击按钮的事件。这在这里工作 https://jsfiddle.net/0fyxws79/2/

03) Fiddle:您可以在哪里看到设计时存在的按钮元素与 stopPropagation 的行为和动态添加的按钮元素之间的差异,这些元素是通过 stopPropagation 动态添加的。
https://jsfiddle.net/uk4ym30r/

$(document).ready( function () {
  $('#example').DataTable();
  $('#example thead tr th').each(function(i, e) {
    $(this).append('<button id="test-button" style="margin-left: 5px; margin-right: 5px;">Test Button</button>');
  });

  $('th[class^="sorting"]').on('click', '#test-button', function(event) {
    alert('test');
    event.stopPropagation();
  });
});

推荐阅读