据我所知,“e”代表Javascript
方法中的“事件”,但我不明白,当我打电话时,如果我想在Javascript
方法中使用下面提到的某些属性,该怎么办?它们。
例如,我可以在此方法中使用e.preventDefault()或e.ctrlKey:
$(".menuItem").click(function (e) {
e.preventDefault();
//Open url in new tab with ctrl key press
if (e.ctrlKey) {
window.open(url, '_blank');
event.stopPropagation();
return false;
}
//... code omitted for brevity
});
但是我不能在从表单元素调用的方法中使用它们,即.menuItem
。是否有可能在下面的方法中使用它?
function TestFunction(e, controller, action) {
e.preventDefault();
//Open url in new tab with ctrl key press
if (e.ctrlKey) {
window.open(url, '_blank');
event.stopPropagation();
return false;
}
//... code omitted for brevity
});
};
更新:我调用TestFunction(),如下所示:
<a onclick="TestFunction('Account', '_Register')" id="test" class="nav-link ">
当我在该方法中使用e “Uncaught ReferenceError:e未定义”时遇到错误。有什么想法吗?
答案 0 :(得分:2)
据我所知,“e”代表Javascript方法中的“事件”
仅按惯例,因为人们使用该名称来声明事件处理程序接收的参数。它可以很容易gonzofish
。
您不能在TestFunction
中使用事件对象,除非调用它对事件做出响应并将事件对象传递给它。
更新:你说过你这样叫TestFunction
:
<a onclick="TestFunction(e, 'Account', '_Register')" id="test" class="nav-link ">
如果是,请将TestFunction
更改为:
function TestFunction(e, controller, action)`
...并在其中始终使用e
(不是event
),并将onclick
属性更改为使用event
,而不是e
:< / p>
<a onclick="TestFunction(event, 'Account', '_Register')" id="test" class="nav-link ">
在onxyz
属性事件处理程序中,event
是一个范围内变量(在大多数浏览器中,它是围绕属性文本创建的生成函数的本地变量;在旧IE上,它是全局的)
旁注:如果没有声明,您可能会定期看到event
(而不是e
)。微软的IE曾经(可能仍然)拥有一个全球event
对象(Chrome决定将针对IE编写的网站扔进骨头并复制它; Firefox没有)。不要使用它。相反,使用适当的事件处理并声明您收到的参数。
附注2:Re TestFunction
,JavaScript中的压倒性惯例是函数名称只有在构造函数时才以大写字母开头(例如,意味着与new
一起使用)。按照惯例,所有其他函数名称应以小写字母开头。当然,您可以选择不遵循惯例,但如果您遵循惯例,它会使您更容易阅读其他人的代码,反之亦然。
答案 1 :(得分:1)
从event-object
inline-click-handler
function TestFunction(e, controller, action) {
var url = 'https://www.google.com'
e.preventDefault();
if (e.ctrlKey) {
window.open(url, '_blank');
e.stopPropagation();
return false;
}
}
<a href="#" onclick="TestFunction(event,'a','b')">Click me!!!</a>
答案 2 :(得分:0)
事件 OR e只能在事件中使用。并且您将在功能中访问。
要在函数中使用,您必须从事件中传递参数。
function TestFunction(controller, action,e) {.....