【发布时间】:2016-09-14 22:51:52
【问题描述】:
我有一个带有select 选项的jQuery DataTables 表(单击时选择行)。我遇到的问题是单击下拉按钮和下拉菜单项会导致选择基础行。 如何防止底层的td/tr/DataTable select点击事件,但允许dropdown及其菜单项(li a子项)点击事件?
<table id="datatable">
<tr>
<td>
<div class="dropdown">
<button type="button" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-caret-down"></i>
</button>
<ul class="dropdown-menu">
<li><a href="#" class="action">Action</a></li>
</ul>
</div>
</td>
</tr>
<tr>
<td>
<div class="dropdown">
<button type="button" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-caret-down"></i>
</button>
<ul class="dropdown-menu">
<li><a href="#" class="action">Action</a></li>
</ul>
</div>
</td>
</tr>
</table>
<script>
$("#datatable").DataTable({ select: true });
</script>
我尝试使用e.stopPropagation(),但这会阻止下拉菜单显示:
<script>
$("#dataTable tbody").on("click", "button", function (e) {
e.stopPropagation(); // this prevents dropdown menu from showing
});
</script>
我也尝试过手动切换下拉菜单,但是这引入了奇怪的下拉行为(例如,单击某一行的下拉按钮会显示其下拉菜单,但没有隐藏任何其他行的已经存在的下拉菜单打开):
<script>
$("#dataTable tbody").on("click", "button", function (e) {
$(this).closest("div.dropdown").toggleClass("open"); // weird effects
// or:
$(this).closest("div.dropdown").find("ul.dropdown-menu").toggle(); // weird effects
e.stopPropagation();
});
</script>
我也试过dropdown("toggle"),虽然这解决了上述奇怪的行为,但它仍然阻止了菜单项的点击事件:
<script>
$("#dataTable tbody").on("click", "button", function (e) {
// no weird behavior, but now menu item click events are disabled
$(this).closest("div.dropdown").find("ul.dropdown-menu").dropdown("toggle");
e.stopPropagation();
});
</script>
【问题讨论】:
标签: twitter-bootstrap drop-down-menu datatables event-propagation