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
Add a ment  | 

2 Answers 2

Reset to default 5

Use 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