jqueryselector,如何不select某些class里面selector
jquery selector, how to not select certain class inside selector
我有如下选择器:
$('#codes-datatable tbody').on('click', 'tr', function () {});
而且我不想让按钮触发此选择器。
例如。我在 table 里面有一个按钮:
<button class="btn">Button</button>
我已经尝试了很多 .not('.btn')
和 :not(.btn)
的组合,但 none 成功了。
请帮忙。
防止这种情况的一种方法是在 tr
s 发生事件绑定后再添加一条语句。
此语句将阻止事件传播,并且仅针对 .btn
s:
$('#codes-datatable tbody tr').on('click', function() {
alert('hello');
});
$('#codes-datatable tbody .btn').on('click', function(e) {
e.stopPropagation();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="codes-datatable">
<tbody>
<tr>
<td>a</td>
<td>b</td>
<td>c</td>
<td>d</td>
<td><button class="btn">Button</button></td>
</tr>
</tbody>
</table>
使用事件委托,您仍然有机会测试 event.target
属性 以根据实际单击的元素处理事件。
// Listen to event on <div> when coming from a <p> element
$('div').on('click', 'p', function (e) {
// Only log if the actual target hasn't a "btn" class.
// Put whatever selector matches elements to filter
if (!$(e.target).is('.btn')) {
console.log(
"Something that doesn't have the 'btn' class set has been clicked!"
);
}
// Process event …
});
br{display: inline-block; margin: 20px 0}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p>
»Hasn't btn class«
<br>
<span class="btn">»Has btn class«</span>
</p>
</div>
我有如下选择器:
$('#codes-datatable tbody').on('click', 'tr', function () {});
而且我不想让按钮触发此选择器。 例如。我在 table 里面有一个按钮:
<button class="btn">Button</button>
我已经尝试了很多 .not('.btn')
和 :not(.btn)
的组合,但 none 成功了。
请帮忙。
防止这种情况的一种方法是在 tr
s 发生事件绑定后再添加一条语句。
此语句将阻止事件传播,并且仅针对 .btn
s:
$('#codes-datatable tbody tr').on('click', function() {
alert('hello');
});
$('#codes-datatable tbody .btn').on('click', function(e) {
e.stopPropagation();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="codes-datatable">
<tbody>
<tr>
<td>a</td>
<td>b</td>
<td>c</td>
<td>d</td>
<td><button class="btn">Button</button></td>
</tr>
</tbody>
</table>
使用事件委托,您仍然有机会测试 event.target
属性 以根据实际单击的元素处理事件。
// Listen to event on <div> when coming from a <p> element
$('div').on('click', 'p', function (e) {
// Only log if the actual target hasn't a "btn" class.
// Put whatever selector matches elements to filter
if (!$(e.target).is('.btn')) {
console.log(
"Something that doesn't have the 'btn' class set has been clicked!"
);
}
// Process event …
});
br{display: inline-block; margin: 20px 0}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p>
»Hasn't btn class«
<br>
<span class="btn">»Has btn class«</span>
</p>
</div>