2011-08-03 39 views
12

我有一個選擇器綁定一個點擊事件,將刪除彈出。不過,我只希望選擇器能夠處理點擊,而不是選擇器的子元素能夠觸發點擊事件。防止點擊孩子發射父母點擊事件

我的代碼:

<div id="popup"> 
    <div class="popup-content">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div> 
</div> 

.popup-content點擊,這將觸發click事件時,我不希望的#popup的孩子這樣做。

jQuery代碼:

$('#popup').bind('click', function() 
{ 
    $(this).remove(); 
}); 
+1

可能重複(http://stackoverflow.com/questions/2244320/jquery-click-event-propagation) –

回答

14

嘗試:

e.stopPropagation(); 
return false; 
在事件處理

+2

'返回FALSE'相同調用'e.stopPropagation ()'*和*'e.preventDefault()'。 –

+0

啊,我對使用'stopPropagation'不太瞭解,謝謝! – MacMac

+0

+1,謝謝你,我也不知道'stopPropagation()' –

0
$('.popup-content').bind('click', function(e) 
{ 
    e.stopPropagation(); 
}); 

$('.popup-content').bind('click', function(e) 
{ 
    return false; 
}); 

在你的情況 - 這是一樣的,但有時你不能做這樣的事情沒有e.stopPropagation()。例如:

$('.popup-content a').bind('click', function(e) 
{ 
    e.stopPropagation(); 
    return confirm("Are you sure?"); 
}); 
18

在爲#popup檢查,如果e.target == this事件處理程序。即:

$('#popup').bind('click', function(e) { 
    if(e.target == this) $(this).remove(); 
}); 

這樣做比將更多的點擊處理程序綁定到所有孩子要容易得多。

+1

感謝您處理父級點擊的替代示例,但允許孩子擁有自己的處理程序。正是我需要檢查。我用'if(!$(e.target).is('a'))'而不是'if(e.target == this)',但是這使我在正確的軌道上。 –

+0

我需要使用if(!$(e.target).is('a'))。我在'每個'功能中使用它(也許使用循環來確定解決方案) –

0
{if(e.target == this){ return;}}); 
[Jquery的點擊事件傳播]的