Click achieve js condition itself rather than the elements of child elements trigger

 

As follows: Click on sub-elements do not want to trigger time

<style>

 

    #parent{
        background: pink;width:50%;
    }
    #child{
        background: orange;height:300px;width: 300px;
    }
</style>

 

<div id="grandFather" οnclick="aa('grandFather',event)">
    <div id="parent" οnclick="aa('parent',event)">
        <div id="child" οnclick="aa('child',event)"></div>
    </div>
</div>


<script>
     function aa(val,event) {

          alert(val);

         console.log(event.target,event.currentTarget)

 

     }

 

</script>

If we want to click on an element, the element's only event triggers, we recommend a simple but not commonly used methods:

e.currentTarget event object returns the current element that triggered the event

e.current return trigger source element of the series of events

Example: If I click on the child element of the parent element will be a bubbling event this trigger, this time aa, will be performed three times in order to:

                 event.target                                 event.currentTarget

child            child                                                 child

parent         child                                                parent

grandFather  child                                             grandFather

 

So realize just click on the element itself, a simple method for the event will trigger elements are as follows: Modify aa function:

 

 

function aa(val,event) {
    if(event.target===event.currentTarget){
        alert(val)
    }

}

 

It is not very simple.

Published 31 original articles · won praise 13 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_38694034/article/details/80092561