How to listen for specific click events but suppress others?
P粉199248808
P粉199248808 2024-04-04 16:55:27
0
1
466

My web application contains an HTML table where each row is linked 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>

Here's 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 these table cells. (I won’t go into details as to why.)

How to suppress redirect when checkbox is selected?

thanks for your help.

P粉199248808
P粉199248808

reply all(1)
P粉980815259

You can check if the target of the event is not a checkbox.

rows.forEach(row => {
  row.addEventListener('click', function(e) {
    if (!e.target.matches('input[type=checkbox]')) handleClick(row);
  });
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template