0

close在它的父级中有一个子按钮,一个通知框。单击父级时,通知框会展开,通知的描述和子按钮在其中可见。

单击该按钮时,应取消展开通知并隐藏其自身和描述。

因为按钮在其父点击事件中有一个点击事件,所以两者都被调用。单击后,我转向让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')没有收到正确的通知。

4

1 回答 1

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(); 

完全删除了选择器,因为您刚刚附加了最后一个元素..

于 2011-12-16T17:37:59.623 回答