简体   繁体   中英

stop click event propagation when clicked inside anchor tag on a div

DESCRIPTION :

I have the following HTML

<a href = "go some where">

<div onclick = "myfunc1(....)">CLICK ME A</div>

<div onclick = "myfunc2(....)">CLICK ME B</div>

</a>

Now when I click the first div the anchor tag gets fired same goes for the second div .. I want to be able to click any div inside the anchor tag and it should just call the function assigned to it ...

if and only if I dont click on any div but the whole other area anchor tag has then it should take me to the page href has...

What Have I Tried :

$(".add_this_person").on("click", "a", function (e) {
    e.preventDefault();
} ); // where add_this_person is a class of both divs

You can try this:-
Add class to both div and change jQuery code like this:-

$(".add_this_person").on("click", "a", function (e) {
  e.preventDefault();
  if($(e.target).is('.first'))
  {
     alert("A");
  }else if($(e.target).is('.second'))
  {
    alert("B");
  }else{
    window.location=$(this).attr('href');
  }
 }); 

Demo

Your attempt is okay but you can use jQuery full potential without using "onclick" events in the div. Just assign a class and make one class event that will fire for all elements with the given class and store the target function in an extra attribute...

Simply place your div tags with action "my-action" and store the target function in a HTML data-trunk "function" with function name as target.

<div class="my-action" data-function="myAction1" >CLICK ME A</div>

<div class="my-action" data-function="myAction2">CLICK ME B</div>


<script type="text/javascript">
    $(document).ready(function() {

        //Declare your functions here, add them to window[] array...
        window.myAction1 = function() {
            alert("A");
        }

        window.myAction2 = function() {
            alert("B");
        }

        //This will trigger whenever an element with class "my-action" is clicked...
        $(document).on("click", ".my-action", function (e) {
            //Just read the function name from data-function and assign it from window[] array
            var targetFunction = window[$(this).data("function")];

            //And execute it, done!
            targetFunction();
        });
    });
</script>

Created a Fiddle which works... http://jsfiddle.net/Lnnffcx5/

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