2011-12-16 17 views
0

我有一個孩子close在它的父母,一個通知框中的按鈕。當單擊父級時,通知框會展開,通知的說明和子級按鈕在其內部可見。e.stopPropagation()和.slideToggle()在點擊事件內部的戰爭

該按鈕,單擊時,應展開通知並隱藏自身和描述。

由於該按鈕在其父級單擊事件中有一個單擊事件,因此兩者都被調用。點擊後,我轉向event.stopPropagation()讓父通知停止重新展開。雖然這阻止了關閉按鈕單擊時發出的通知,但它提出了一個我不明白的新問題。

在我的測試中,我設置了兩個通知,均未展開。當我點擊通知時,它會展開並顯示說明和關閉按鈕。當我點擊關閉按鈕時,通知未展開,按鈕和說明被隱藏。 但是,我發現說明和關閉按鈕出現在另一個通知!

代碼:

var $NotificationContainer = $("#NotificationContainer"); 
    $NotificationContainer.append('<div class="Notification" title="'+title+'"></div>'); 

    var $thisNotification = $NotificationContainer.children('.Notification[title='+title+']'); 
    $thisNotification.append('<div class="NotificationTitle">'+title+'</div>'); 
    $thisNotification.append('<div class="NotificationDescription">'+description+'</div>'); 
    $(".NotificationDescription").hide(); 

    // Button used to close an expanded notification 
    $thisNotification.append("<div class='NotificationCloseButton'></div>"); 
    $('.NotificationCloseButton').hide(); 

    // When the parent notification box is clicked 
    $thisNotification.click(function(event) 
    { 
     $thisNotification.animate({height:250}, 1000); 
     $thisNotification.find('.NotificationDescription').slideToggle('fast'); 
     $thisNotification.find('.NotificationCloseButton').slideToggle('fast'); 
    }); 

    // When the child close button is clicked 
    $(".NotificationCloseButton").click(function(event) 
    { 
     event.stopPropagation(); 
     $thisNotification.animate({height:50}, 1000); 
     $thisNotification.find('.NotificationDescription').slideToggle('fast'); 
     $thisNotification.find('.NotificationCloseButton').slideToggle('fast'); 
    }); 

我不知道怎麼$thisNotification.find('element')沒有抓住右報告。

+1

您可以張貼通知的HTML結構中的最後一個元素..選擇? – Blender 2011-12-16 17:32:25

+0

實際上我沒有一個特定的HTML文件/代碼,但是如果你喜歡,我可以發佈CSS嗎? – Briz 2011-12-16 17:45:46

回答

1

請問如果你改變了事件處理

// When the parent notification box is clicked 
    $thisNotification.click(function(event) 
    { 
     var self = $(this); 
     self.animate({height:250}, 1000); 
     self.find('.NotificationDescription').slideToggle('fast'); 
     self.find('.NotificationCloseButton').slideToggle('fast'); 
    }); 

    // When the child close button is clicked 
    $(".NotificationCloseButton").click(function(event) 
    { 
     var self = $(this); 
     event.stopPropagation(); 
     self.animate({height:50}, 1000); 
     self.find('.NotificationDescription').slideToggle('fast'); 
     self.find('.NotificationCloseButton').slideToggle('fast'); 
    }); 

用於this來識別,而不是依靠在創建元素定義的變量clicked元素,它的工作(避免環路,其中病例所有元素參考)分配給該變量的最後值..


此外,由於要附加到#NotificationContainer你可以選擇的最後一個項目,而不是尋找相同的冠軍。

var $thisNotification = $NotificationContainer.children().last(); 

完全刪除,因爲你剛纔附加