我正在使用嵌套的点击事件(有大量图像,有些带有子图像,有些没有)。
对所有图像(儿童,父母和非父母)进行Onclick,它们应显示在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;
});
}
}
});
<img button title id alt />
<input radio id="layer-{ID}-{item.ID}-radio" name="layer-{ID}" value="{item.ID}" class="item-button" data-multi="{item.PARENT}" data-layer="{ID}" data-item="{item.ID}" />
<!-- IF item.CHILD1 != 0 -->
<div id="child-{item.ID}" style="width: 300px; position: absolute; display: none;">
<img button here title data-layer="{item.CLAYER1}" data-item="{item.CHILD1}">
<input radio id="layer-{item.CLAYER1}-{item.CHILD1}-radio" name="layer-{item.CLAYER1}" value="{item.CHILD1}" style="display: none;" class="item-sub1" data-clayer="{item.CLAYER1}" data-citem="{item.CHILD1}" />
答案 0 :(得分:3)
我认为您需要做的是防止事件冒泡DOM树并阻止任何父处理程序收到事件通知,这是使用stopPropagation()
方法。
$('.item-button').click(function(event) {
event.stopPropagation();
// your code...
欲了解更多信息: 1. jquery 2. javascript