2

Inside that I have other child divs. Those have child divs too.

<div class="parent">
<div class="child_1">//children elements</div>
<div class="child_1">//children elements</div>
<div class="child_1">//children elements</div>
<div class="child_1">//children elements</div>
</div>

I want to add a click event that fires when I click any element inside parent div, including parent div, excluding child_1 div and its descendants.

Currently I tried with

jQuery(".parent").not(".child_1").click(function(event) {

});

But the click event works when I click on child_1 div and it's descendants.

What is the problem here? please help.

UPDATE

here i have another click event for child_1

jQuery(".child_1").click(function(event) {

});
4

5 回答 5

5

你应该这样做。

$('.parent').on('click', function () {
  // do your stuff here
}).find('.child_1').on('click', function (e) {
  e.stopPropagation();
});

这是一个小提琴http://jsfiddle.net/BbX7D/1/

于 2013-05-06T07:39:34.333 回答
1

您仍然必须在要排除的元素上捕获点击事件,否则点击只会冒泡到.parent元素。

使用该closest方法检查被点击的元素是否是具有 class 的元素,或者是其子元素.child_1。用于stopPropagation防止事件冒泡:

$('.parent,.parent *').click(function(e){
  if ($(this).closest('.child_1').length > 0) {
    alert('in child_1');
  } else {
    alert('not in child_1');
  }
  e.stopPropagation();
});

演示:http: //jsfiddle.net/Guffa/tETCQ/

于 2013-05-06T07:39:59.153 回答
0

试试这个(小提琴):

(编辑+更新小提琴) 我发现了一个缺陷。此版本检查单击的元素是否在或位于具有“排除”类的元素内:

<div class="parent">
<div class="child_1 exclude">//children elements</div>
<div class="child_1">//children elements</div>
<div class="child_1">//children elements</div>
<div class="child_1">//children elements</div>
</div>

jQuery(".parent").click(function(event) 
    {
    if ($(event.target).closest('.exclude').length>0) return false; 
    alert('hi');
    });
于 2013-05-06T07:31:46.190 回答
0

我认为应该是

jQuery(".parent, .parent *").not(".child_1").click(function(event) {

});
于 2013-05-06T07:20:22.413 回答
0

有点老问题,但我想我会放弃我的决议,以防它帮助其他人。

这几乎就是我所做的。此示例使用您的标记:

$('.parent').on('click', function(e) {
    var $target = $(e.target);
    if (!$target.parents('.child_1').length && !$target.hasClass('child_1')) {
        // do what you need on the parent's click event
        // add 'e.preventDefault()' here if you need
    }
    // no need to prevent default or stop propagation here
    // this will allow click events on child elements to work
});
于 2016-10-14T17:33:47.943 回答