如何监听特定的点击事件但抑制其他事件?

huangapple go评论60阅读模式
英文:

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:

&lt;table&gt;
  &lt;tr data-url=&quot;https://www.google.com&quot;&gt;
    &lt;td&gt;Google&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr data-url=&quot;https://www.yahoo.com&quot;&gt;
    &lt;td&gt;Yahoo&lt;/td&gt;
  &lt;/tr&gt;
&lt;/table&gt;

This is the Javascript to make it work:

const rows = document.querySelectorAll(&#39;table tr[data-url]&#39;);

rows.forEach(row =&gt; {
  row.addEventListener(&#39;click&#39;, 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 =&gt; {
  row.addEventListener(&#39;click&#39;, function(e) {
  	if (!e.target.matches(&#39;input[type=checkbox]&#39;)) handleClick(row);
  });
});

huangapple
  • 本文由 发表于 2023年5月23日 01:51:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76308775.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定