jQuery重叠div不会使div的隐藏onclick无效

Joh*_*ith 1 html javascript css jquery

jQuery('#warning').click(function() {
  console.log('clicked at warning');
});

jQuery('#content').click(function() {
  console.log('clicked at content');
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="warning">
  <div id="content">This is the content</div>
  dsfdfsdsfdsfdsfdsfdsfdsf
</div>
Run Code Online (Sandbox Code Playgroud)

小提琴:https://jsfiddle.net/73jykhj0/

不幸点击content也会触发点击warning.如何消除点击warning

Sat*_*pal 7

防止事件冒泡使用 event.stopPropagation()

jQuery('#warning').click(function() {
  console.log('clicked at warning');
});

jQuery('#content').click(function(event) {
  event.stopPropagation()
  console.log('clicked at content');
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="warning">
  <div id="content">This is the content</div>
  dsfdfsdsfdsfdsfdsfdsfdsf
</div>
Run Code Online (Sandbox Code Playgroud)


或者,您可以使用event.target必要的方式检查事件的目标.

jQuery('#warning').click(function(event) {
  if ($(event.target).is('#content')) {
    return;
  }
  console.log('clicked at warning');
});

jQuery('#content').click(function() {
  console.log('clicked at content');
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="warning">
  <div id="content">This is the content</div>
  dsfdfsdsfdsfdsfdsfdsfdsf
</div>
Run Code Online (Sandbox Code Playgroud)