是否有可能只在顶部元素上使用jQuery.click触发器? [英] Is it possible to have jQuery.click trigger on the top element only?

查看:95
本文介绍了是否有可能只在顶部元素上使用jQuery.click触发器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个网站,用户可以点击任何元素来编辑它的CSS。我使用以下命令将click函数添加到所有lis,div和uls。

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 lis, divs and uls.

$('li,div,ul').click(function () {  

alert(this.id); 

});

问题是,如果我点击一个li元素,那么我会得到它的警报,任何它下面的元素。 (所有容器)。

The problem is if I click on an 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?

推荐答案

你想要停止事件传播,你可以通过调用 stopPropagation 方法。

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); 
});

这篇关于是否有可能只在顶部元素上使用jQuery.click触发器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆