我在行点击上附加了一个事件,在复选框内更改了一个复选框。
如何防止首先触发该行点击?
$(document).on('click', 'table tr', function() {
console.log('row');
})
$(document).on('change', 'table tr input[type="checkbox"]', function() {
console.log('chk');
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<table>
<tr>
<td>
<input type="checkbox">
</td>
</tr>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</body>
</html>
答案 0 :(得分:2)
将内部元素上要处理的事件从change
更改为click
。
change
事件在click
事件之后 之后才触发。单击事件在复选框上触发,然后冒泡到该行。完成后,将在复选框上触发更改事件。
$(document).on('click', 'table tr', function() {
console.log('row');
})
$(document).on('click', 'table tr input[type="checkbox"]', function() {
console.log('chk');
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<table>
<tr>
<td>
<input type="checkbox">
</td>
</tr>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</body>
</html>
答案 1 :(得分:0)
还为复选框添加了单击事件以停止事件传播。请检查此提示。
答案 2 :(得分:0)
使用jquery选择器:not
排除tr单击复选框,然后停止将子元素事件传播到父tr。
$(document).on('click', 'table tr :not(input[type="checkbox"])', function(e) {
console.log('row');
});
$(document).on('click', 'table tr input[type="checkbox"]', function(e) {
console.log('chk');
e.stopImmediatePropagation();
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<table>
<tr>
<td>
<input type="checkbox">
</td>
<td>another td</td>
</tr>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</body>
</html>