问题
I have see a lot tutorial that tell me the way to prevent bubble is use "e" parameter
just like :
function(e){
e.preventDefault()
}
but in some situation,the firebug tell me it is wrong with "e is not define"
so is there a way to stop the bubble without the parameter e?
回答1:
If you set an event handler by using an element attribute (say, <button onclick="myFunc()">
) the argument list will be empty. You have to use <button onclick="myFunc(event)">
instead to pass the current event as an argument. No argument will be passed to the callback function by default.
event
is a special variable in this case. When using <element onEVENT="code">
the browser creates a new script and a function with the FunctionBody
"code". This function will then take one argument event
, thus you can use this object in your own function/code (see w3c:ehca). Note that IE creates a global object event
for every triggered event.
So pass event
as an additional variable and use e.preventDefault() and e.stopPropagation. Note that return false;
won't cancel the propagation in a click
event.
Demonstrations:
- Demonstration showing the arguments of the callback function when using jQuery,
<element onclick="">
andHTMLElementObject.onclick
. - return false; vs e.stopPropagation(); (spoiler:
return false;
fails.)
References:
- W3C: DOM Level 3: stopPropagation
- W3C: DOM Level 3: preventDefault
W3C: HTML5 Event handler content attribute:
Using the script execution environment created above, create a function object (as defined in ECMAScript edition 5 section 13.2 Creating Function Objects), with:
Parameter list FormalParameterList
If the attribute is the onerror attribute of the Window object
- Let the function have three arguments, named
event
,source
, andfileno
.
Otherwise
- Let the function have a single argument called
event
.
- Let the function have three arguments, named
来源:https://stackoverflow.com/questions/9766232/is-there-a-way-stop-bubble-in-javascript-without-e-parameter