Javascript 嵌套单击事件冒泡问题
我正在处理一个嵌套的单击事件(有一个大的图像数组,一些有子图像,一些没有子图像) 单击所有图像(子图像、父图像和非父图像),它们应该显示在一个diff css div中,然后如果再次单击,则会无限期地删除它们自己 到目前为止,此代码适用于父图像和非父图像,但冒泡使子图像显示父图像 如果我在子函数之前返回false以停止冒泡,它将破坏数组中较低位置的父图像和非父图像的功能(子图像位于新的弹出css中,而不是列表中),但是如果我不停止冒泡,嵌套的单击事件将不会运行 有没有人能想出一个好办法来解决这个烂摊子Javascript 嵌套单击事件冒泡问题,javascript,jquery,Javascript,Jquery,我正在处理一个嵌套的单击事件(有一个大的图像数组,一些有子图像,一些没有子图像) 单击所有图像(子图像、父图像和非父图像),它们应该显示在一个diff css div中,然后如果再次单击,则会无限期地删除它们自己 到目前为止,此代码适用于父图像和非父图像,但冒泡使子图像显示父图像 如果我在子函数之前返回false以停止冒泡,它将破坏数组中较低位置的父图像和非父图像的功能(子图像位于新的弹出css中,而不是列表中),但是如果我不停止冒泡,嵌套的单击事件将不会运行 有没有人能想出一个好办法来解决这个
// Click an image, and it will change it in the demo css class panel
$('.item-button').data('status','not_clicked');
$('.item-button').click(function(event) {
var layerID = $(this).attr('data-layer'); //these do not correspond to actual layers of nesting.
var itemID = $(this).attr('data-item');
var itemmulti = $(this).attr('data-multi'); //this value def works to recognize parent from other non-parent items (not children).
var clayerID = $(this).attr('data-clayer');
var citemID = $(this).attr('data-citem'); //child item 1.
if(( $(this).data('status') == 'clicked') || itemID == 0) {
var imageSrc = $(this).parent().find('img').attr('id');
$(layerID).attr('src', imageSrc);
} else {
$(this).data('status','clicked');
var imageSrc = $(this).parent().find('img').attr('id');
$(layerID).attr('src', imageSrc);
if (itemmulti != 0) {
//begin headache.
document.getElementById('child-' + itemID).style.display = "inline-block";
//this is where a separate click function for children items begins.
$('.item-sub1').data('status','unclicked');
$('.item-sub1').click(function(event) {
if(( $(this).data('status') == 'click') || citemID == 0) {
var imageSrc = $(this).parent().find('img').attr('id');
$(selector).attr('src', imageSrc);
} else {
$(this).data('status','click');
var imageSrc = $(this).parent().find('img').attr('id');
$(clayerID).attr('src', imageSrc);
}
return false;
});
}
}
});
我认为要防止事件在DOM树中冒泡并防止任何父处理程序收到事件通知,需要做的是使用
stopPropagation()
方法
$('.item-button').click(function(event) {
event.stopPropagation();
// your code...
有关更多信息:
1.
2. 也请发布你的HTML标记。我怀疑这与事件冒泡无关。我看到您的代码有两个奇怪的地方:(1)从另一个单击事件中绑定一个单击事件;(2) 三种不同的点击状态(“未点击”、“点击”和“点击”)。如果您在JSFIDLE上发布一个工作版本(或不工作),可能有人会帮助调试您的代码。实际上有4种单击状态,单击、未单击、单击和未单击。一个用于每个差异状态,两个用于每个单击事件,以确保我的理智。我认为在点击事件中绑定点击事件是整个问题的症结所在……我将尝试JSFIDLE。
$('.item-button').click(function(event) {
event.stopPropagation();
// your code...