何时在函数(Javascript)中将事件作为参数传递?
我不熟悉Javascript事件,我遇到了许多示例,其中何时在函数(Javascript)中将事件作为参数传递?,javascript,jquery,events,Javascript,Jquery,Events,我不熟悉Javascript事件,我遇到了许多示例,其中event作为参数传递给函数。因此,必须将事件传递给每个函数,以及何时不传递。如下所示,代码事件在第二个函数中传递。我不知道什么时候通过,什么时候不通过 var elem = document.getElementById('my-elem'); elem.addEventListener('click', function(){ //the element has been clicked... do stuff here }, fa
event
作为参数传递给函数。因此,必须将事件
传递给每个函数,以及何时不传递。如下所示,代码事件在第二个函数中传递。我不知道什么时候通过,什么时候不通过
var elem = document.getElementById('my-elem');
elem.addEventListener('click', function(){
//the element has been clicked... do stuff here
}, false);
$('#my-elem').click(function(e) {
//the element has been clicked... do stuff here
});
如果您的问题是哪个错误处理程序获得传递的事件对象,那么答案是全部 通过
addEventListener
或其他库(如示例jQuery)添加的所有函数都会获得一个事件
对象作为第一个参数
但是,JavaScript允许您向函数传递比实际需要更多的参数。因此,提供一个不接受事件参数的函数是没有错误的,因为该函数仍然可以通过浏览器等方式调用。否,
您不必在函数上传递事件
您必须获取元素,并且在调用要应用于元素的函数之后
下面是一个应用于按钮的函数的小示例
$(“#按钮1”)。在('click',function()上{
警报(“点击”);
});代码>
点击我
在这种情况下,您没有传递e(事件),而是在函数中接收它。单击#我的元素时,浏览器将以事件作为第一个参数调用此函数。您的函数将此元素作为e接收。一旦到了那里,你就可以看到
e.target
依此类推。如果您不传递该事件,它将由浏览器在所有标准事件触发器中自动完成。问题是,您是否需要在所有函数中以命名参数的形式接收事件,答案是,这完全取决于您是否要使用它:
您需要访问活动的时间:
element.addEventListener("click", foo);
// You can explicitly declare a function argument that will represent
// the event object that is automatically passed to you by the browser
function foo(evt){
// And, then you can access the event in the function
evt.xyz...
}
element.addEventListener("click", foo);
// The event is still passed to the function, but now, you don't
// have an explicit way to access it:
function foo(){
}
当您不需要访问活动时:
element.addEventListener("click", foo);
// You can explicitly declare a function argument that will represent
// the event object that is automatically passed to you by the browser
function foo(evt){
// And, then you can access the event in the function
evt.xyz...
}
element.addEventListener("click", foo);
// The event is still passed to the function, but now, you don't
// have an explicit way to access it:
function foo(){
}
同样,事件将在所有情况下传递,因此如果您决定使用参数捕获引用,则不会提高或降低性能。作为入门的一般经验法则,最好养成为它添加命名参数的习惯,这样如果需要访问它,就可以轻松地获得它。如果需要使用它(例如对其调用stopPropagation()),请在函数中命名它。正如idmean所说,无论您是否在函数定义中命名它,它都将被传递。因为您只是声明了一个回调,所以不是您在进行“传递”。您正在传递一个函数。调用该函数时,将使用事件参数调用该函数。如果你能说出它的名字:
function (e) {}
然后您可以使用
e.stopPropagation()
如果不是,则必须使用arguments对象访问它