我看过很多教程,告诉我防止气泡的方法是使用“e”参数
就像:
function(e){
e.preventDefault()
}
但在某些情况下, Firebug 告诉我“e is not Define”是错误的
那么有没有办法不用参数e就可以阻止气泡呢?
最佳答案
如果您使用元素属性(例如 <button onclick="myFunc()">
)设置事件处理程序,则参数列表将为空。您必须使用<button onclick="myFunc(event)">
而是将当前事件作为参数传递。默认情况下不会向回调函数传递任何参数。
event
在这种情况下是一个特殊变量。使用时<element onEVENT="code">
浏览器创建一个新脚本和一个带有 FunctionBody
的函数“代码”。然后,该函数将采用一个参数 event
,因此您可以在自己的函数/代码中使用此对象(请参阅 w3c:ehca )。请注意,IE 创建了一个全局对象 event
对于每个触发的事件。
所以通过event
作为附加变量并使用 e.preventDefault()
和 e.stopPropagation
。请注意return false;
不会取消 click
中的传播事件。
演示:
- Demonstration显示使用 jQuery 时回调函数的参数,
<element onclick="">
和HTMLElementObject.onclick
. -
return false;
vse.stopPropagation();
(剧透:return false;
失败。)
引用文献:
- 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
关于javascript - 有没有办法在没有 "e"参数的情况下阻止 JavaScript 中的气泡?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9766232/