2011-02-23 32 views

回答

11

作爲一個更通用的解決方案,你應該在containerclick事件處理程序檢查e.target

$('.container').click(function(e) { 
    // If you want to ignore clicks to anything inside the `.container` div: 
    if (!$(e.target).hasClass('container')) return; 
    // or, if you only want the `.inside` div to not fire the event, 
    if ($(e.target).hasClass('inside')) return; 

    // container do something here 
}); 

這樣你就不會阻止事件的傳播,這會破壞綁定live處理程序。

+0

優秀的答案!謝謝! – Roubi 2016-12-09 00:39:01

1

添加click事件處理程序內部如下:

$('.inside').click(function(event) { 
    // do anything you might want with the click for inside 
    return false; // prevents click event from bubbling up the DOM hierarchy 
}); 

另外,event.stopPropagation()也防止起泡,像這樣:

$('.inside').click(function(event) { 
    // do anything you might want with the click for inside 
    event.stopPropagation(); // prevents click event from bubbling up the DOM hierarchy 
}); 

This article解釋事件冒泡。

+0

點擊事件對我來說不起作用,而mousedown事件工作正常,但是當我拖動並移動裏面的div [可拖動插件應用]時,容器事件再次觸發 – qinHaiXiang 2011-02-23 15:31:49

+0

@qinHaiXiang - 你檢查過什麼事件的目標是當它到達容器時,如[本答案]中所述(http://stackoverflow.com/questions/5092675/how-to-cancel-click-event-of-container-div-trigger-當點擊元素 - 這-INSI/5092899#5092899)?是內部div還是容器div? – justkt 2011-02-23 15:45:27

5
$('.inside').click(function(e) { 
    e.stopPropagation(); 
}); 

這應該適合你。它停止任何點擊內部div從冒泡到容器。

這裏有一個簡單的例子,以及 -

+1

編號'stopPropagation()'通常是一個糟糕的主意,在這種情況下具體做錯了一件事:https://css-tricks.com/dangers-stopping-event-propagation/ – SystemParadox 2015-10-08 13:03:03

相關問題