我已经将一个点击处理程序附加到表格行元素,我需要一些帮助来从点击处理程序中排除带有子菜单类的元素。
我尝试使用jQuery :not 选择器成功排除整个 td 元素,但这不是我想要的。
以下代码需要jQuery,Bootstrap和FontAwesome才能生效。请参考上面的JsFiddle链接。
HTML
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Details</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>123</td>
<td>Name 1
<div class="pull-right sub-menu">
<div class="btn-group">
<button type="button" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown"><i class="fa fa-chevron-down"></i>
</button>
<ul class="dropdown-menu pull-right" role="menu">
<li><a href="#">Edit</a></li>
<li><a href="#">Delete</a></li>
<li><a href="#">Block</a></li>
</ul>
</div>
</div>
</td>
<td>New User</td>
<td>Pending</td>
</tr>
</tbody>
</table>
的Javascript
$(function() {
$('table tr').on('click', function() {
alert('Clicked');
});
});
** - 编辑 - **
更新了JsFiddle。我在下面添加了评论,并附上了答案。
// The below "if" condition is the ANSWER.
答案 0 :(得分:3)
一种解决方案是查看点击的目标是否在具有类sub-menu
$(function() {
$('table tr').on('click', function(e) {
if (!$(e.target).closest('.sub-menu').length) {
//do your stuff
alert('Clicked');
}
});
});
&#13;
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" />
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Details</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>123</td>
<td>Name 1
<div class="pull-right sub-menu">
<div class="btn-group">
<button type="button" class="btn btn-default btn-xs dropdown-toggle edit-asset" data-toggle="dropdown" style="border: none;">
<i class="fa fa-chevron-down"></i>
</button>
<ul class="dropdown-menu pull-right" role="menu">
<li><a href="#">Edit</a></li>
<li><a href="#">Delete</a></li>
<li><a href="#">Block</a></li>
</ul>
</div>
</div>
</td>
<td>New User</td>
<td>Pending</td>
</tr>
</tbody>
</table>
&#13;
答案 1 :(得分:1)
您可以使用stopPropagation来阻止点击传播到tr:
$('.sub-menu').on('click', function(e){
e.stopPropagation();
});