如何在具有不同行为(onclick)的标记中的<span>上添加行为(onclick)?

时间:2016-01-03 00:35:30

标签: javascript jquery html css

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

是否有任何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() { ... });

3 个答案:

答案 0 :(得分:1)

当您点击span元素时,您在技术上仍然会点击tr元素(因为span是后代元素,并且事件冒泡到{ {1}}元素)。

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

请参阅this example

span

答案 1 :(得分:0)

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

我在手机上,所以希望这是有道理的......

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

答案 2 :(得分:0)

它被称为event propagation,在js中非常经典。

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

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