javascript - 如何阻止 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>
解决方案
看看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();
});
});
推荐阅读
- android - 制作用于预填充 Room 数据库的预打包 .db 文件
- nginx - Nginx处理两步301/302
- macos - 如何在mac终端上获取多页pdf的图像大小?
- javascript - 在 Node.js 中将 setTimeout 与请求包一起使用
- asp.net - 在一行中设置验证码图像和文本框
- php - 通过下拉列表过滤数据库表
- php - 使用 SET 数据类型和 PDO 调用 MySql 存储过程时出现错误 'Data truncated for column ...'
- vim - 如何将 Vim 命令保存到特定缓冲区并再次使用它们
- php - 为什么 PHP setcookie 可以在 localhost 上工作,但不能在浏览器上工作?
- python-3.x - OSError:Errno 30 只读文件系统:有什么方法可以在 AWS Lambda 中创建 CSV 并将其附加到来自 Python 的电子邮件?