从另一个div顶部的div获取click事件

时间:2015-11-08 14:58:54

标签: javascript jquery html css

这是UI片段的样子

enter image description here

我让垃圾桶在点击时工作正常但是那时我没有在蓝色div上有点击事件。既然我在蓝色div上也有一个点击事件,当我点击垃圾桶时,我得到的是蓝色div对象而不是垃圾桶对象。我尝试了一些z-index技巧,但这没有用。

任何帮助表示感谢。

<td id="ea-13" class="activityTableCell">
    <div style="width:90px; margin-left:0px" class="eventTimeSpan"></div>
    <div id="NewActivityContainer-13" class="activityContainerExisting">
        <div data-uid="57386445" class="label label-sm label-info newActivityClass point" style="width:59px; top:-1px; left:30px; z-index:4000" title="Mobile Game Party">
        Mobile Game Party 
            <div data-isactivity="1" data-packageid="" data-elid="57386445" class="xRemove" style="left:46px;z-index:8000"><i class="fa fa-trash font-red" title="Remove"></i>
            </div>
        </div>
    </div>
</td>

点击代码:

$(document).on("click", ".newActivityClass", function(){
    console.log(this);
    ...snip...
}

$(document).on("click", ".xRemove,.aRemove", function(){
...snip...
}

2 个答案:

答案 0 :(得分:3)

您可以尝试event.stopPropagation()

$(document).on("click", ".xRemove,.aRemove", function(event){
   event.stopPropagation();
   // code here
});

来源:https://api.jquery.com/event.stoppropagation/

答案 1 :(得分:1)

如前所述,event.stopPropagation()为您完成工作。

对于JsFiddle代码:https://jsfiddle.net/peacock/r0kk5ps9/

&#13;
&#13;
$(document).on("click", "#inner", function(e){
   alert("clicked inner");
    e.stopPropagation();
});


$(document).on("click", "#outer", function(e){
   alert("clicked outer");
   e.stopPropagation();
});
&#13;
#outer {
    width : 100px;
    height : 100px;
    background-color: #777777;
}

#inner {
    position: relative;
    top : 50%;
    left:50%;
    width : 30px;
    height : 30px;
    background-color: #232323;
}
    
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="outer"> 
    <div id="inner">
    </div>
</div>
&#13;
&#13;
&#13;