0

我们遇到了一个经典问题,即 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');
});

我发现这段代码是在单击关闭按钮时:

  • 滑动切换要隐藏的描述
  • SlideToggles 关闭按钮被隐藏
  • 容器未展开,但随后重新展开(内容仍隐藏)

$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;
});
4

1 回答 1

1

您有父对象的单击绑定:

$thisNotification

对于子对象:

$(".NotificationCloseButton")

当您单击关闭按钮时,两个处理程序都会触发“单击”事件,所有动画都会排队,并且您会得到不希望的关闭然后打开操作。

您有几个选项可以解决此问题。#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();
});
于 2011-12-15T22:23:23.523 回答