如何通过点击孩子来避免点击父母?

时间:2018-06-15 16:34:46

标签: javascript

<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点击titlewraptitle下面的空白区域)

2 个答案:

答案 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事件

&#13;
&#13;
$(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;
&#13;
&#13;