我有一個歸類foobar
,而且DIV是unclassed裏面幾個的DIV一個DIV,但我想他們都繼承了foobar
類:如何讓點擊事件只在父DIV上觸發,而不是孩子?
$('.foobar').on('click', function() { /*...do stuff...*/ });
我要在某處點擊時只火了DIV但不在其子女DIV上。
我有一個歸類foobar
,而且DIV是unclassed裏面幾個的DIV一個DIV,但我想他們都繼承了foobar
類:如何讓點擊事件只在父DIV上觸發,而不是孩子?
$('.foobar').on('click', function() { /*...do stuff...*/ });
我要在某處點擊時只火了DIV但不在其子女DIV上。
如果e.target
與this
的元素相同,那麼您沒有單擊後代。
$('.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>
//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/
你可以在你贊成使用冒泡:
$('.foobar').on('click', function(e) {
// do your thing.
}).on('click', 'div', function(e) {
// clicked on descendant div
e.stopPropagation();
});
這看起來像是我的特定場景的一個很好的解決方案,因爲我只想排除點擊次數在後裔''元素。只有一個問題:當我中間點擊它們時,事件仍然會觸發(在Google Chrome中進行測試)。有沒有這種變種也可以防止這種情況? – cgogolin 2015-10-19 09:23:20
$(".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
})
還有,如果你不介意的話只針對新瀏覽器的作品的另一種方式。只需添加CSS
pointer-events: none;
您想要捕獲點擊的任何孩子的div。這裏的支撐臺
我有同樣的問題,這個解決方案(基於其他答案)
$(".newsletter_background").click(function(e) {
if (e.target == this) {
$(".newsletter_background").hide();
}
});
基本上它說,如果目標是div然後運行上來代碼,否則什麼都不做(不要隱藏它)
這答案解釋[this](http://stackoverflow.com/questions/9146163/jquery-closest-with-attribute-filter#comment11499568_9146163)評論 – gdoron 2012-02-07 20:44:35
@gdoron:亞當太善良了。 :) – 2012-02-07 20:47:44
可以請你回答我的[問題](http://stackoverflow.com/q/9193293/601179)... =) – gdoron 2012-02-08 15:16:25