如何确保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);
}
答案 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
相同。
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;
答案 2 :(得分:0)
您可以执行以下操作;
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;