是否有可能只在顶部元素上使用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);
});