Javascript 如何防止父div在单击子类时注册单击;event.stopPropagation();做有趣的事

Javascript 如何防止父div在单击子类时注册单击;event.stopPropagation();做有趣的事,javascript,jquery,jquery-events,stoppropagation,Javascript,Jquery,Jquery Events,Stoppropagation,我们遇到了一个典型的问题,div的子节点被点击,父节点的点击事件也被触发。我在一个容器中设置了一个按钮,它可以在单击时展开和取消展开 单击按钮时,应: 打开容器 隐藏容器的描述 下面给出了两个单击功能: var $NotificationContainer = $("#NotificationContainer"); $NotificationContainer.append('<div class="Notification" title="'+title+'"></di

我们遇到了一个典型的问题,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
对于子对象:

$(".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();
});

按钮是否在描述中?如果是,请仅滑动切换说明。否,按钮不在说明内。这两个都是分别附加到
$thisNotification
的。您能否仅隐藏此通知?我不确定您的意思。你能澄清一下吗?很抱歉我不确定这两行代码调用的是什么黑魔法:
var$thisNotification$thisNotification.append(…
$thisNotification
指向什么?也许您应该搜索现有元素,而不是尝试在
null
上调用
append
。当我运行这两行时,出现错误
无法调用未定义的
的方法'append'。
$thisNotification.click(function()
{
    notificationClickHandler(); //animations are separated from bindings
    $thisNotification.unbind('click');
});
$(".NotificationCloseButton").click(function()
{
    $thisNotification.animate({height:50}, 1000);
    $(this).find('.NotificationDescription').slideToggle('fast');
    $(this).find('.NotificationCloseButton').slideToggle('fast');
    $.clearQueue();
});