简体   繁体   中英

How can I prevent an event from being activated in a child element?

I would like the event not to be activated in the input.

My code html

<header>
    <nav class="titlebar" ondblclick="test()">
       <input class="box" type="text">
       <hr> 
    </nav>
</header>

my code js

function test() {
alert('holi')

}

You can conditionally check for the input. If you would like to avoid more elements, you can check for a characteristic like class name.

 function test(e) { if(e.target instanceof HTMLInputElement && e.target.type == 'text') { console.log("INput clicked"); } else { console.log("somewhere else"); } } 
 <header> <nav class="titlebar" ondblclick="test(event)"> <input class="box" type="text"> <hr> </nav> </header> 

Another way would be to attach a listener to the child element:

 function test() { console.log("clicked container"); } function stop(event) { event.stopPropagation(); //Stops propagation to parent } 
 <header> <nav class="titlebar" ondblclick="test(event)"> <input class="box" type="text" ondblclick="stop(event)"> <hr> </nav> </header> 

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