英文:
How to listen to specific click events but suppress others?
问题
我的网络应用程序包含一个HTML表格,其中每一行链接到特定的URL:
<table>
<tr data-url="https://www.google.com">
<td>Google</td>
<td><input type="checkbox"></td>
</tr>
<tr data-url="https://www.yahoo.com">
<td>Yahoo</td>
<td><input type="checkbox"></td>
</tr>
</table>
这是使其工作的JavaScript代码:
const rows = document.querySelectorAll('table tr[data-url]');
rows.forEach(row => {
row.addEventListener('click', function(event) {
if (event.target.type !== 'checkbox') {
handleClick(row);
}
});
});
function handleClick(row) {
const url = row.dataset.url;
window.document.location = url;
}
这段代码可以正常工作。现在,当选中复选框时,不会发生重定向。
英文:
My web application contains an HTML table where each row links to a specific URL:
<table>
<tr data-url="https://www.google.com">
<td>Google</td>
</tr>
<tr data-url="https://www.yahoo.com">
<td>Yahoo</td>
</tr>
</table>
This is the Javascript to make it work:
const rows = document.querySelectorAll('table tr[data-url]');
rows.forEach(row => {
row.addEventListener('click', function() {
handleClick(row);
});
});
function handleClick(row) {
const url = row.dataset.url;
window.document.location = url;
}
This code works great.
Now my client wants me to add checkboxes to those table cells. (I won't go into detail why.)
How can I suppress the re-direct when a checkbox gets selected?
Thanks for your help.
答案1
得分: 2
你可以检查事件的目标是否不是复选框。
rows.forEach(row => {
row.addEventListener('click', function(e) {
if (!e.target.matches('input[type=checkbox]')) handleClick(row);
});
});
英文:
You can check if the event's target is not a checkbox.
rows.forEach(row => {
row.addEventListener('click', function(e) {
if (!e.target.matches('input[type=checkbox]')) handleClick(row);
});
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论