简体   繁体   中英

How to disable onclick function from child selector using javascript

How can i make sure that onclick events only fires by clicking on td not on the span ?

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


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

You have to add an event listener to the inner child and cancel the propagation of the event.

In plain JS something like

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

is sufficient. Note that jQuery provides the same facility :

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

or

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

Assuming you want to prevent clicks on all sub-elements, pass the event to getDetails and have it see if event.currentTarget is the same as event.target .

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

You may do as follows;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM