admin 管理员组文章数量: 1086019
Suppose I have HTML like this:
<div>
<a href="">Google</a>
</div>
And I have an event handler like this (suppose I have jQuery available):
$('div').on('click', function(ev) {
// ...
});
Is it possible, from within that event handler, to prevent the default action of the <a>
link? Or is it too late? (In other words, am I required to attach an event on the <a>
or lower to prevent the default link action, or is it possible to stop it in the above handler).
As said above, I have jQuery available if the solution requires it.
Suppose I have HTML like this:
<div>
<a href="http://google.com">Google</a>
</div>
And I have an event handler like this (suppose I have jQuery available):
$('div').on('click', function(ev) {
// ...
});
Is it possible, from within that event handler, to prevent the default action of the <a>
link? Or is it too late? (In other words, am I required to attach an event on the <a>
or lower to prevent the default link action, or is it possible to stop it in the above handler).
As said above, I have jQuery available if the solution requires it.
Share Improve this question edited Oct 14, 2020 at 18:42 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked May 11, 2012 at 20:53 Ben LeeBen Lee 53.3k15 gold badges128 silver badges146 bronze badges 1- Could you check the event.target.nodeName for A vs DIV? – j08691 Commented May 11, 2012 at 21:06
2 Answers
Reset to default 10This will definitely work:
$('div').on('click', "a", function(e) {
e.preventDefault();
});
Here's a fiddle: http://jsfiddle.net/xvKNC/1/
Hold on. this seems to work fine for me in Chrome
// prevent default on every click in the div
$('div').on('click', function(ev) {
ev.preventDefault();
});
See the updated fiddle: http://jsfiddle.net/xvKNC/2/
It seems to work:
$('div').on('click', function(ev) {
ev.stopImmediatePropagation();
ev.preventDefault();
});
JSFiddle: http://jsfiddle.net/3yFfC/
本文标签:
版权声明:本文标题:jquery - In Javascript, how to preventDefault on a child element from within parent event handler - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1739482990a2059759.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论