admin管理员组文章数量:1318983
I have a html element with an onclick attribute and I need to prevent that event from bubbling up. I tried doing this:
<div onclick="event.stopPropagation();">
and this:
<div onclick="(function(event){event.stopPropagation();})();)">
But neither works. I absolutely need to do this in the html onclick attribute since this div is part of a Razor partial view and the script is set on the ViewData dictionary. How do I call event.stopPropagation() on the html onclick attribute?
Edit: the error in this case is that event is null. So for some reason, I can´t access the event like this.
I have a html element with an onclick attribute and I need to prevent that event from bubbling up. I tried doing this:
<div onclick="event.stopPropagation();">
and this:
<div onclick="(function(event){event.stopPropagation();})();)">
But neither works. I absolutely need to do this in the html onclick attribute since this div is part of a Razor partial view and the script is set on the ViewData dictionary. How do I call event.stopPropagation() on the html onclick attribute?
Edit: the error in this case is that event is null. So for some reason, I can´t access the event like this.
Share Improve this question edited Jul 25, 2016 at 13:48 Magnus asked Jul 25, 2016 at 13:43 MagnusMagnus 5142 gold badges7 silver badges22 bronze badges 4- I don't know Razor, or the ViewData dictionary; but can you not link to a function to do this? – David Thomas Commented Jul 25, 2016 at 13:46
- 2 Possible duplicate of How to stop event propagation with inline onclick attribute? – Liam Commented Jul 25, 2016 at 13:48
- event.stopPropagation(); should be working. Have you tried not making it an inline onclick event? MDN Reference - developer.mozilla/en-US/docs/Web/API/Event/stopPropagation – Renzo Gaspary Commented Jul 25, 2016 at 13:48
- You have an error in your second code: there is an unmatched close parenthesis. Also, why did you make it in a self-invoking function? – Jonathan Lam Commented Jul 25, 2016 at 13:50
2 Answers
Reset to default 5Use event.stopPropagation method of Event
. There is a mistake in your second code snippet where you do not pass event
to the anonymous function. Fixed code:
<div onclick="(function(e) { e.preventDefault(); e.stopPropagation(); })(event)">
The onclick inline function is implemented as:
function(event) {
}
So you can just use the 'event' variable.
<div onclick='event.stopPropagation(); event.preventDefault()'>
There is no need to implement inline functions. Your first example should work if you add the event.preventDefault().
本文标签: javascriptHow to stop event propagation on onclick event in html attributeStack Overflow
版权声明:本文标题:javascript - How to stop event propagation on onclick event in html attribute? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742056124a2418305.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论