简体   繁体   中英

Multiple click events inside one element

I have the following HMTL code:

<li>
    <img .../>
    <img .../>
    <img .../>
</li>

I want to register different functions for each element (one for the list item, and three other for the images). I registered click events on all but when I click the images, the li function triggers.

li.addEventListener("click",open,false);
img1.addEventListener("click",edit,false);
img2.addEventListener("click",delete,false);
img3.addEventListener("click",add,false);

I googled what happens when you set to true the last parameter but still no luck.

Thanks for all the help.

When you define your functions, stop event from propagating like so:

function open(e) {
   e.stopPropagation();
}

function edit(e) {
   e.stopPropagation()
}

and so on...

expanding on designcise's answer... you need to use e.stopPropagation() to stop the event from bubbling up

$('li img').on('click',function(e){
    e.stopPropagation();
    alert('img clicked');
});

here a jsfiddle http://jsfiddle.net/hbGRS/

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