2013-05-06 28 views
2

在裏面我還有其他子div。那些孩子也有。消除一個div上的點擊事件,排除一個子div並且它的後代

<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> 

我想補充一點,火災,當我點擊任何元素內部格,包括格,不包括child_1格及其後代一個click事件。

目前,我試着用

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

}); 

但是當我點擊child_1 DIV和它的後代click事件的作品。

這裏有什麼問題?請幫忙。

UPDATE

在這裏,我有child_1

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

}); 
+0

ü可以在發送烏爾的jsfiddle例如... – PraJen 2013-05-06 07:23:21

回答

0

另一個click事件,我認爲它應該是

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

}); 
0

試試這個(fiddle):

(編輯+更新小提琴) 我發現了一個缺陷。此版本檢查單擊的元素是否在類別爲「排除」的元素內:

<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'); 
    }); 
+0

我用排除類,因爲所有你的孩子被稱爲child_1。你也可以使用'$(event.target).closest('。parent')。children()。get(0)== event.target'。僅在'上使用點擊事件。如果你沒有明確地取消其他孩子可能擁有的任何點擊功能的傳播,父母將會正常工作。 – Rembunator 2013-05-07 08:10:27

5

您應該這樣做。

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

這裏是一個小提琴http://jsfiddle.net/BbX7D/1/

1

你還是要趕上你要排除的元素click事件,否則點擊只會泡到.parent元素。

使用closest方法來檢查點擊的元素是否爲.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/

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