我有一张 table 。这是它的示例代码。
<table>
<thead>
<tr>
<td>filename</td>
<td>file size</td>
<td>date</td>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox">
file 1
</td>
<td>
1MB
</td>
<td>
13-01-12
</td>
</tr>
<tr>
<td>
<input type="checkbox">
file 2
</td>
<td>
2MB
</td>
<td>
23-12-17
</td>
</tr>
</tbody>
</table>
我在每行都有一个复选框输入,用于选择表中的多个 tr。我还需要重定向到文件 onclick 的详细 View 。所以,这是我的 JS 代码
$(document).on("click", "table tbody tr", function() {
window.location = $(this).data('href');
});
现在,每当我尝试单击复选框时,tr 就会被单击。因此,该页面被重定向到另一个页面。但选择不起作用。如何防止点击选择时页面重定向。
提前致谢
更新::
我想在 gmail 中实现收件箱邮件等功能。每当我点击任何一封邮件时,它就会被打开。如果我选中该复选框,则会选择相应的邮件。
最佳答案
当一个元素被点击时,它会冒泡到 DOM 中附加了点击事件的最高点。防止您的复选框触发 <tr>
上的点击事件的,你需要停止“冒泡”。
将其添加到您的代码中:
$('input:checkbox').on("click", function(e){
e.stopPropagation();
});
来源:How do I prevent a parent's onclick event from firing when a child anchor is clicked?
关于javascript - 选择多个 tr 并在单次 tr 单击时重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52891739/