将“事件"作为参数传递给函数 [英] Passing 'event' into the function as an argument

查看:131
本文介绍了将“事件"作为参数传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JS和jQuery的新手,对于在什么情况下需要将event作为参数传递给函数,以及在什么情况下不需要,我有些困惑.强烈需要.

I'm novice with both JS and jQuery, and I'm a little bit confused about what situations would require you to pass event as an argument into the function, and what situations you would not need to.

例如:

      $(document).ready(function() {

        $('#foo').click(function() {
         // Do something
});

      });

      $(document).ready(function() {

        $('#foo').click(function(event) {
         // Do something
});

      });

推荐答案

event参数有一些用途.如果您实际上要使用它,则只需将其指定为处理程序的参数即可-JavaScript处理可变数量的参数而不会产生投诉.

The event argument has a few uses. You only need to specify it as an argument to your handler if you're actually going to make use of it -- JavaScript handles variable numbers of arguments without complaint.

您将看到的最常见用法是防止触发事件的操作的默认行为.所以:

The most common use you'll see is to prevent the default behavior of the action that triggered the event. So:

$('a.fake').click(function(e) {
    e.preventDefault();
    alert("This is a fake link!");
});

...单击后,将停止与类fake的任何链接实际转到其href.同样,您可以使用它取消表单提交,例如在验证方法中.这类似于 return false,但更可靠.

...would stop any links with the class fake from actually going to their href when clicked. Likewise, you can cancel form submissions with it, e.g. in validation methods. This is like return false, but rather more reliable.

jQuery的event对象实际上是除IE之外所有内容中提供的标准event参数的跨浏览器版本.从本质上讲,它是一种快捷方式,它使您仅使用一个代码路径,而不必检查每个事件处理程序中使用的浏览器.

jQuery's event object is actually a cross-browser version of the standard event argument provided in everything but IE. It's essentially a shortcut, that lets you use only one code path instead of having to check what browser you're using in every event handler.

(如果您阅读非jQuery代码,则会看到很多以下内容,以解决IE的不足.

(If you read non-jQuery code you'll see a lot of the following, which is done to work around IE's deficiency.

function(e) {
    e = e || window.event; // For IE

这很痛苦,而库使它更容易处理.)

It's a pain, and libraries make it so much easier to deal with.)

在jQuery文档中对其属性进行了完整的说明.本质上,包括如果您在那看到任何您需要的东西,别担心.我喜欢始终包含它,只是这样,如果我确定毕竟需要它,就永远不必记住以后再添加它.

There's a full accounting of its properties in the jQuery docs. Essentially, include it if you see anything you need there, and don't worry otherwise. I like to include it always, just so I never have to remember to add it in later if I decide that it's needed after all.

这篇关于将“事件"作为参数传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆