简体   繁体   中英

Is it possible to have jQuery.click trigger on the top element only?

I'm trying to make a site where the user can click on any element to edit it's CSS. I use the following to add the click function to all <li> , <div> and <ul> .

$('li,div,ul').click(function () {
    alert(this.id);
});

The problem is if I click on a <li> element, then I get the alert for that and any element underneath it. (all the containers).

Is it possible to have only the top element trigger when clicked?

You want to stop event propagation, you do this in jQuery by calling the stopPropagation method on the event object.

$('li,div,ul').click(function (e) {  
    e.stopPropagation();
    alert(this.id); 
});

I believe you'd want to use stopPropagation(); inside the click function.

It sounds to me like you're looking for .stopPropagation() . Calling stopPropagation will prevent the event from "bubbling" up to parent containers.

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