admin管理员组文章数量:1356894
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
2 Answers
Reset to default 6Mouse events are triggered like this way
MouseDown
Click
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.
版权声明:本文标题:javascript - How to stop a parent's click event when the child's mousedown event is fired - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744024916a2577870.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论