如何在<span>在<tr>具有不同行为的标签(onclick)

How to add behaviour (onclick) on <span> in a <tr> tag which has different behaviour (onclick)?

本文关键字:gt lt 标签 onclick span tr      更新时间:2023-09-26

我有一个数据table,它在每行中都有一个span元素。当有人点击<tr>元素时,执行JS代码。当有人点击<span>元素时,会执行另一个JS代码。问题是,即使我单击了<span>元素,它也经常检测到对<tr>的单击。

有什么javascript/jquery函数可以帮我吗?

HTML代码

<table class="table">
  <thead>
    <tr>
      <th></th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr class="behaviourTr">
      <td></td>
      <td></td>
      <td></td>
      <td><span class="glyphicon glyphicon-pencil"></span>
      </td>
    </tr>
  </tbody>
</table>

JS代码

$('.behaviourTr').on('click', function() { ... });
$('.glyphicon-pencil').on('click', function() { ... });

当您单击span元素时,从技术上讲,您仍然在单击tr元素(因为span是子元素,事件气泡一直到tr元素)。

tr点击事件监听器中,您可以检查event.target(它是被点击的元素),看看span元素是否没有被点击。在下面的代码段中,is()方法用于确定event.target是否是而不是span元素。

请参见此示例。

$('.behaviourTr').on('click', function(e) {
  if (!$(e.target).is('span')) {
    // The tr was clicked, but the span wasn't
  }
});

它被称为事件传播,在js中非常经典。

实际上,还有另一种方法是通过停止传播,而不是通过检测目标。

演示在这里。http://jsbin.com/sufede/edit?html,css,js,输出

在回调函数中,您需要检查实际导致事件的元素。我敢打赌,您的多个元素需要一次点击事件。

我在打电话,所以希望这有意义。。。

$('.behaviourTr').on('click', function(e) {
 var targetElm = $(e.currentTarget);
If(targetElm.is('.glyphicon-pencil')){
//the pencil was clicked
}
If(targetElm.is('.behaviourTr')){
//the tr was clicked
}
});

e.target==元素侦听事件

e.currentTarget=触发事件的元素