![](/img/trans.png)
[英]How to prevent the same event registering on ancestor elements when Event.stopPropagation doesn't work?
[英]How to prevent the parent div from registering the click when a child class is clicked; event.stopPropagation(); doing funny things
我們遇到了一個經典問題,即 div 的子級被點擊,而父級的點擊事件也被觸發。 我在容器中設置了一個按鈕,單擊時可以展開和展開。
單擊該按鈕時,應:
下面給出了兩個點擊函數:
var $NotificationContainer = $("#NotificationContainer");
$NotificationContainer.append('<div class="Notification" title="'+title+'"></div>');
var $thisNotification = $NotificationContainer.children('.Notification[title='+uniqueTitle+']');
$thisNotification.append('<div class="NotificationDescription">'+uniqueDescription+'</div>');
$(".NotificationDescription").hide();
// Button used to close an expanded notification
$thisNotification.append("<div class='NotificationCloseButton'></div>");
$('.NotificationCloseButton').hide();
$thisNotification.click(function()
{
$(this).animate({height:250}, 1000);
$(this).find('.NotificationDescription').slideToggle('fast');
$(this).find('.NotificationCloseButton').slideToggle('fast');
});
$(".NotificationCloseButton").click(function()
{
$thisNotification.animate({height:50}, 1000);
$(this).find('.NotificationDescription').slideToggle('fast');
$(this).find('.NotificationCloseButton').slideToggle('fast');
});
我用這段代碼發現的是,當點擊關閉按鈕時:
正在調用$thisNotification
點擊(我認為)。
現在,當我嘗試使用event.stopPropagation();
或簡單的return false;
在 closeButton 的點擊中,我得到了非常有趣的結果。
現在單擊帶有上述任一添加項的關閉按鈕:
我實現 stopPropogation 並返回 false 的確切方式的代碼片段:
$(".NotificationCloseButton").click(function(event)
{
event.stopPropagation();
$thisNotification.animate({height:50}, 1000);
$(this).find('.NotificationDescription').slideToggle('fast');
$(this).find('.NotificationCloseButton').slideToggle('fast');
});
和
$(".NotificationCloseButton").click(function()
{
$thisNotification.animate({height:50}, 1000);
$(this).find('.NotificationDescription').slideToggle('fast');
$(this).find('.NotificationCloseButton').slideToggle('fast');
return false;
});
您具有父對象的單擊綁定:
$thisNotification
對於子對象:
$(".NotificationCloseButton")
當您單擊關閉按鈕時,兩個處理程序都會觸發 'click' 事件,所有動畫都在排隊,並且您會得到不希望的關閉然后打開操作。
您有幾個選項可以解決此問題。 #1 是取消綁定父單擊處理程序並在單擊關閉按鈕后重新綁定它。
$thisNotification.click(function()
{
notificationClickHandler(); //animations are separated from bindings
$thisNotification.unbind('click');
});
或者,jQuery 有一個 .clearQueue() 方法可以刪除所有排隊的動畫。 當用戶快速使用鼠標時,或者如果您的頁面大量使用 jQuery 動畫,這可能會產生副作用,因此您必須為您的應用程序嘗試適當的范圍級別。
$(".NotificationCloseButton").click(function()
{
$thisNotification.animate({height:50}, 1000);
$(this).find('.NotificationDescription').slideToggle('fast');
$(this).find('.NotificationCloseButton').slideToggle('fast');
$.clearQueue();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.