<div class='titlewrap'>
<div class='title'>lorem ipsum</div>
<div class='title'>lorem ipsum</div>
<div class='title'>lorem ipsum</div>
<br><br>
</title>
我想右键点击titlewrap
vs title
。
JS
$(document).on('contextmenu', '.titlewrap', function(e) {
e.preventDefault();
console.log('titlewrap');
});
$(document).on('contextmenu', '.title', function(e) {
e.preventDefault();
console.log('title');
});
点击title
给出双控制台结果:
titlewrap
title
如何仅通过点击title
获取title
并保持titlewrap
点击titlewrap
(title
下面的空白区域)
答案 0 :(得分:1)
尝试将stopPropagation添加到.title函数中,如此
$(document).on('contextmenu', '.titlewrap', function(e) {
e.preventDefault();
console.log('titlewrap');
});
$(document).on('contextmenu', '.title', function(e) {
e.preventDefault();
e.stopPropagation();
console.log('title');
});
答案 1 :(得分:1)
使用event.stopPropagation()阻止事件冒泡到父级并触发其事件。您仍然可以通过右键单击titlewrap
元素未涵盖的区域来触发title
事件
$(document).on('contextmenu', '.titlewrap', function(e) {
e.preventDefault();
console.log('titlewrap');
});
$(document).on('contextmenu', '.title', function(e) {
e.preventDefault();
e.stopPropagation();
console.log('title');
});
&#13;
.titlewrap {
padding:10px;
border:black solid 1px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='titlewrap'>
<div class='title'>lorem ipsum</div>
<div class='title'>lorem ipsum</div>
<div class='title'>lorem ipsum</div>
</div>
&#13;