如何使用javascript从子选择器禁用onclick功能

时间:2017-09-07 12:47:07

标签: javascript jquery onclick

如何确保onclick事件仅通过点击 td 而不是跨度来触发?

<td style="cursor: pointer;" onclick="getDetails(13,3)">
   <span class="responsiveExpander"></span>
    TEST
</td>


function getDetails(table_id,id)
{
   alert(table_id + id);
}

3 个答案:

答案 0 :(得分:3)

您必须向内部子项添加事件侦听器并取消事件的传播。

在简单的JS中像

document.getElementById('inner').addEventListner('click',function (e){
   e.stopPropagation();
});

就足够了。请注意jQuery provides the same facility

$(".inner-div").click(function(event){
    event.stopPropagation();
});  

$(".inner-inner").on('click',function(event){
    event.stopPropagation();
});  

答案 1 :(得分:2)

假设您要阻止对所有子元素的点击,请将event传递给getDetails并让其查看event.currentTarget是否与event.target相同。

&#13;
&#13;
function getDetails(event, table_id, id) {
   if (event.currentTarget !== event.target) {
     return; // clicked a sub-element
   }
   alert(table_id + id);
}
&#13;
span {
 color: red;
}
&#13;
<table>
<tr>
<td style="cursor: pointer;" onclick="getDetails(event, 13,3)">
   <span class="responsiveExpander">SHOULD NOT ALERT</span>
    TEST
</td>
</tr>
</table>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以执行以下操作;

&#13;
&#13;
data.addEventListener("click", function(e){
                                 e.target === this && console.log("td clicked");
                               });
&#13;
td {border: red solid 2px;}
span{color: white; background-color: black}
&#13;
<table>
  <tr>
    <td id="data" style="cursor: pointer">
      <span>SPAN:</span> TEST
    </td>
  </tr>
</table>
&#13;
&#13;
&#13;