Javascript 如何在<;上添加行为(onclick);span>;在a<;tr>;具有不同行为的标签(onclick)?

Javascript 如何在<;上添加行为(onclick);span>;在a<;tr>;具有不同行为的标签(onclick)?,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我有一个数据表,每行都有一个span元素。当有人单击元素时,就会执行JS代码。当有人点击元素时,另一个JS代码被执行。 问题是,即使我单击了元素,它也经常检测到对的单击 有什么javascript/jquery函数可以帮助我吗 HTML代码 <table class="table"> <thead> <tr> <th></th> <th></th> <th&g

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

有什么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>

当您单击
span
元素时,从技术上讲,您仍然在单击
tr
元素(因为
span
是一个后代元素,事件会冒泡到
tr
元素)

tr
click事件侦听器内部,您可以检查
event.target
(被单击的元素)以查看
span
元素是否未被单击。在下面的代码段中,
is()
方法用于确定
event.target
是否不是
span
元素


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

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

$('.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==触发事件的元素

调用它,这在js中非常经典

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


演示就在这里。

span元素上的click事件正在冒泡到tr元素。您需要取消span元素中的事件。可理解的解释和有效的解决方案!谢谢你,先生!:)
$('.behaviourTr').on('click', function(e) {
  if (!$(e.target).is('span')) {
    // The tr was clicked, but the span wasn't
  }
});
$('.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
}

});