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