最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to stop a parent's click event when the child's mousedown event is fired - Stack Overflow

programmeradmin0浏览0评论

As described in the title, I want to stop a parent's click event when the child's mousedown event is fired.

My HTML code looks like this

<div class='parent'> 
       <div class='child'></div>
</div>

my jquery code looks like this

 $('.child').mousedown(function(){
   //what can I write here to prevent parent's click event from fireing?
   //I've tried event.stopPropagation() as well as
   //event.stopImmediatePropagation() already 
   });

 $('.parent').on('click',function(){...})

As described in the title, I want to stop a parent's click event when the child's mousedown event is fired.

My HTML code looks like this

<div class='parent'> 
       <div class='child'></div>
</div>

my jquery code looks like this

 $('.child').mousedown(function(){
   //what can I write here to prevent parent's click event from fireing?
   //I've tried event.stopPropagation() as well as
   //event.stopImmediatePropagation() already 
   });

 $('.parent').on('click',function(){...})
Share Improve this question asked Jul 22, 2016 at 2:37 Lin ShenLin Shen 5951 gold badge8 silver badges22 bronze badges 2
  • 1 Have you tried event.stopPropagation() on a click handler for the child element? – nnnnnn Commented Jul 22, 2016 at 2:39
  • Yes, i've tried $('.child'').on('click',function(event){ event.stopPropagation()console.log('child click');}); And the funny thing is: the click event of .child doesn't always triggled, while the mousedown event of .child and the click event of .parent works as usual. – Lin Shen Commented Jul 22, 2016 at 2:54
Add a ment  | 

2 Answers 2

Reset to default 6

Mouse events are triggered like this way

  1. MouseDown

  2. Click

  3. MouseUp

event.stopPropagation() in mousedown handler only affects on mousedown event. You can try this workaround:

var mdFaired = false;

$('.parent').click(function(e) {
  if(!mdFaired) {
      var counter = $(this).children('.counter');
      var count = parseInt(counter.text());
      counter.text(++count);
  }
  else {
    mdFaired = false;
  }
});

$('.child').mousedown(function(e) {
  e.stopPropagation();
  mdFaired = true;
  
  var counter = $(this).children('.counter');
  var count = parseInt(counter.text());
  counter.text(++count);
});
div {
  border: 1px solid black;
  padding: 5px;
}

.parent {
  width: 300px;
  height: 300px;
}

.child {
  width: 50%;
  height: 50%;
  margin: 50px auto;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='parent'>
  <span class="counter">0</span>
  <div class='child'>
    <span class="counter">0</span>
  </div>
</div>

e.stopPropagation();
e.preventDefault();

e is event passed from function call.

Should do the trick.

发布评论

评论列表(0)

  1. 暂无评论