简体   繁体   中英

Cancel click event of parent element only

I having div structure.

<div id="parentDiv">
    Employee Data
   <a>Click Here</a>
</div>

Parent div's click event is all ready registered by third party plug in, its not in control of me. Its doing some validation on that div click.

I want to perform some action on click of anchor tag 'Click Here', but don't want to perform validation, registered for div click.

But when user click 'Employee Data' it should perform validation as registered for click event.

I tried

<a onclick="(arguments[0]||window.event).stopPropagation();">Click Here</a>
<a onclick="(arguments[0]||window.event).cancelBubble=true;"></a>

But it cancel his own click event ie anchor tags click event.

stopPropagation() is exactly what you require, however you need to call it directly on the click event that was raised. You can do that using jQuery, like this:

 $('#parentDiv').click(function() { console.log('parent clicked'); }) $('#parentDiv a').click(function(e) { e.stopPropagation(); console.log('child clicked'); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="parentDiv"> Employee Data <a href="#">Click Here</a> </div> 

Alternatively, you can use native JS like this:

 document.querySelector('#parentDiv').addEventListener('click', function() { console.log('parent clicked'); }) document.querySelector('#parentDiv a').addEventListener('click', function(e) { e.stopPropagation(); console.log('child clicked'); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="parentDiv"> Employee Data <a href="#">Click Here</a> </div> 

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