我正在为移动设备创建一个菜单,我想添加一个叠加点击功能。
当我点击菜单(紫色部分)时,它不需要关闭,但是当我点击蓝色部分时,它需要关闭。
我写了一个 jQuery,它只有紫色部分,但是当我点击蓝色部分时,alert
没有出现。
会有我的JSFiddle测试,看看。
这是我的代码
$('.outer-content .inner-content').on('click', function() {
$(".outer-content .inner-content").data('clicked', 'yes');
var isClicked = $('.outer-content').data('clicked');
if (isClicked == 'yes') {
alert("clicked the blue block");
} else {
alert("clicked the purple block");
}
});
.outer-content {
width: 100%;
height: 200px;
background: lightblue;
position: relative;
}
.inner-content {
width: 300px;
background: purple;
position: absolute;
margin: auto;
top: 0;
bottom: 0;
right: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="outer-content">
<div class="inner-content"></div>
</div>
最佳答案
javascript 中基本上有两种事件模型。事件捕获和事件冒泡。在事件冒泡中,如果您单击内部 div,则首先触发内部 div 的单击事件,然后触发外部 div 的单击事件。在事件捕获中,首先触发外部 div 事件,然后触发内部 div 事件。要停止事件传播,请在您的点击方法中使用此代码。
e.stopPropagation();
您的代码:
$('.outer-content').on('click', function(e) {
alert("clicked the blue block");
});
$('.inner-content').on('click', function(e) {
alert("clicked the purple block");
e.stopPropagation();
});
.outer-content {
width: 100%;
height: 200px;
background: lightblue;
position: relative;
}
.inner-content {
width: 300px;
background: purple;
position: absolute;
margin: auto;
top: 0;
bottom: 0;
right: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer-content">
<div class="inner-content"></div>
</div>
关于javascript - 如何使用 Jquery 检测到内部 div 的点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42644995/