在没有点击事件的情况下检索没有父母的div [英] Retrieve a div without parents on click event
问题描述
我正在编写一个应用程序,需要返回一个我单击过的元素的类.
I'm writing an application and I need to return a class of an element that I have clicked on.
问题是,一旦我单击某个元素,我还将获得所有的父类.
Problem is that once I click on an element, I also get all of it's parents classes.
我用来检索类名的代码:
Code I use to retrieve class names:
$('div').click(function () {
console.log($(this).attr("class"));
});
这是元素的示例:
<div class="parent">
<div class="child">
Bla bla bla
</div>
</div>
一旦我单击.child div
,它就会同时返回.child
和.parent
类名.
Once I click on a .child div
, it returns me both .child
and .parent
class names.
我想应该有一种简单的方法来解决此问题,但是经过几个小时的研究,我什么都找不到.
I suppose there should be an easy way to fix this, but after a couple of hours of research I couldn't find anything.
推荐答案
您需要防止事件冒泡到父元素,请使用return false;
You need to prevent the event from bubbling to the parent elements, use return false;
$('div').click(function (e) {
console.log($(this).attr("class"));
return false; // or e.stopPropagation();
});
在jQuery事件处理程序内的中的 阅读此绝佳答案,以获取更多信息. Read this excellent answer for more info. 对于 With 这篇关于在没有点击事件的情况下检索没有父母的div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!return false
与在传递的e.stopPropagation
/category/events/event-object/"rel =" nofollow noreferrer> jQuery.Event对象. ................. return false
from within a jQuery event handler is effectively the same as calling both e.preventDefault
and e.stopPropagation
on the passed jQuery.Event object. ........<div>
,e.stopPropagation()
和return false
之间现在有所区别,因为<div>
没有像<a>
或< button>
那样的默认点击事件.<div>
there is now difference between e.stopPropagation()
and return false
because <div>
doesn't have a default click event like <a>
or <button>
do.