e.stopPropagation()和.slideToggle()在war内部点击事件

时间:2011-12-16 17:30:59

标签: javascript jquery click slidetoggle stoppropagation

我的父级内部有一个子close按钮,一个通知框。单击父级时,通知框将展开,通知的说明和子级按钮在其中可见。

单击此按钮时,应取消通知并隐藏自身和说明。

因为该按钮在其父点击事件中有一个点击事件,所以两者都被调用。我点击后转向event.stopPropagation()让父通知停止重新展开。虽然这使得通知无法通过单击关闭按钮进行扩展,但它提出了一个我不明白的新问题。

在我的测试中,我设置了两个通知,两个都未展开。当我点击通知时,它会展开并显示说明和关闭按钮。单击关闭按钮时,将隐藏通知expandpands以及按钮和说明。 但是,我发现其他通知中出现了说明和关闭按钮!

代码:

    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 个答案:

答案 0 :(得分: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(); 

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