2012-02-07 45 views

回答

315

如果e.targetthis的元素相同,那麼您沒有單擊後代。

$('.foobar').on('click', function(e) { 
 
    if (e.target !== this) 
 
    return; 
 
    
 
    alert('clicked the foobar'); 
 
});
.foobar { 
 
    padding: 20px; background: yellow; 
 
} 
 
span { 
 
    background: blue; color: white; padding: 8px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div class='foobar'> .foobar (alert) 
 
    <span>child (no alert)</span> 
 
</div>

+0

這答案解釋[this](http://stackoverflow.com/questions/9146163/jquery-closest-with-attribute-filter#comment11499568_9146163)評論 – gdoron 2012-02-07 20:44:35

+0

@gdoron:亞當太善良了。 :) – 2012-02-07 20:47:44

+0

可以請你回答我的[問題](http://stackoverflow.com/q/9193293/601179)... =) – gdoron 2012-02-08 15:16:25

17
//bind `click` event handler to the `.foobar` element(s) to do work, 
//then find the children of all the `.foobar` element(s) 
//and bind a `click` event handler to them that stops the propagation of the event 
$('.foobar').on('click', function() { ... }).children().on('click', function (event) { 
    event.stopPropagation(); 
    //you can also use `return false;` which is the same as `event.preventDefault()` and `event.stopPropagation()` all in one (in a jQuery event handler) 
}); 

這將停止click事件的傳播(鼓泡)在任何.foobar元件(一個或多個)的孩子元素(多個)因此事件不會到達.foobar元素以觸發其事件處理程序。

這裏是一個演示:http://jsfiddle.net/bQQJP/

19

你可以在你贊成使用冒泡:

$('.foobar').on('click', function(e) { 
    // do your thing. 
}).on('click', 'div', function(e) { 
    // clicked on descendant div 
    e.stopPropagation(); 
}); 
+0

這看起來像是我的特定場景的一個很好的解決方案,因爲我只想排除點擊次數在後裔''元素。只有一個問題:當我中間點擊它們時,事件仍然會觸發(在Google Chrome中進行測試)。有沒有這種變種也可以防止這種情況? – cgogolin 2015-10-19 09:23:20

2
$(".advanced ul li").live('click',function(e){ 
    if(e.target != this) return; 
    //code 
    // this code will execute only when you click to li and not to a child 
}) 
22

還有,如果你不介意的話只針對新瀏覽器的作品的另一種方式。只需添加CSS

pointer-events: none; 

您想要捕獲點擊的任何孩子的div。這裏的支撐臺

http://caniuse.com/#feat=pointer-events

+2

這是最好的黑客,謝謝 – Rickie 2016-08-17 14:37:45

+0

好的解決方案,謝謝。 – tulsluper 2017-01-19 14:24:49

+1

知道我應該避免寫'感謝'的評論,但我可以吻你這腳:-) – 2017-03-29 09:24:26

0

我有同樣的問題,這個解決方案(基於其他答案)

$(".newsletter_background").click(function(e) { 
    if (e.target == this) { 
     $(".newsletter_background").hide(); 
    } 
}); 

基本上它說,如果目標是div然後運行上來代碼,否則什麼都不做(不要隱藏它)

相關問題