jQuery:如何在事件处理函数中获取事件对象而不将其作为参数传递? [英] jQuery: How to get the event object in an event handler function without passing it as an argument?

查看:97
本文介绍了jQuery:如何在事件处理函数中获取事件对象而不将其作为参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的链接上有一个 onclick 属性:

I have an onclick attribute on my link:

<a href="#" onclick="myFunc(1,2,3)">click</a>

指向JavaScript中的此事件处理程序:

That points to this event handler in JavaScript:

function myFunc(p1,p2,p3) {
    //need to refer to the current event object:
    alert(evt.type);        
}

由于事件对象evt不传递给参数,是不是还有可能获得这个对象吗?

Since the event object "evt" is not passed to a parameter, is it still possible to obtain this object?

我尝试过 window.event $(window .event),但都是 undefined

任何想法?

推荐答案


由于事件对象evt没有从参数传递,是否仍然可以获取对象?

Since the event object "evt" is not passed from the parameter, is it still possible to obtain this object?

不,不可靠。 IE和其他一些浏览器使它可以作为 window.event (不是 $(window.event)),但很多浏览器不会。

No, not reliably. IE and some other browsers make it available as window.event (not $(window.event)), but many browsers don't.

您最好将事件对象传递到函数中:

You're better off passing the event object into the function:

<a href="#" onclick="myFunc(event, 1,2,3)">click</a>

即使在非IE浏览器上也是如此,因为它们在上下文中执行代码, c $ c>事件变量(并且在IE上工作,因为事件解析为 window.event )。我在IE6 +,Firefox,Chrome,Safari和Opera中尝试过。示例: http://jsbin.com/iwifu4

That works even on non-IE browsers because they execute the code in a context that has an event variable (and works on IE because event resolves to window.event). I've tried it in IE6+, Firefox, Chrome, Safari, and Opera. Example: http://jsbin.com/iwifu4

但您的

But your best bet, by far, is to hook up the event properly:

HTML:

<a href="#">click</a>

使用jQuery的JavaScript(由于您使用jQuery):

JavaScript using jQuery (since you're using jQuery):

$("selector_for_the_anchor").click(function(event) {
    // Call `myFunc`
    myFunc(1, 2, 3);

    // Use `event` here at the event handler level, for instance
    event.stopPropagation();
});

...或者如果你真的想通过事件 into myFunc

...or if you really want to pass event into myFunc:

$("selector_for_the_anchor").click(function(event) {
    myFunc(event, 1, 2, 3);
});

选择器可以是标识锚点的任何东西。您有一个非常丰富的集可供选择(几乎所有的CSS3,加上一些)。您可以向锚点添加 id class ,但是您还可以选择其他选项。如果你可以在文档中使用它,而不是添加一些人为的东西,那么很棒。

The selector can be anything that identifies the anchor. You have a very rich set to choose from (nearly all of CSS3, plus some). You could add an id or class to the anchor, but again, you have other choices. If you can use where it is in the document rather than adding something artificial, great.

这篇关于jQuery:如何在事件处理函数中获取事件对象而不将其作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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