最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is it possible to have jQuery.click trigger on the top element only? - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question edited Jan 23, 2020 at 10:06 ankitkanojia 3,1224 gold badges24 silver badges37 bronze badges asked Feb 25, 2009 at 4:52 user70687user70687
Add a comment  | 

3 Answers 3

Reset to default 20

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.

发布评论

评论列表(0)

  1. 暂无评论