如何获得onclick调用对象? [英] How to get the onclick calling object?

查看:79
本文介绍了如何获得onclick调用对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在onclick事件的调用对象上有一个处理程序。

i need to have a handler on the calling object of onclick event



ie

<a href="123.com" onclick="click123(event);">link</a>
<script>
function click123(event)
{
//i need <a> so i can manipulate it with Jquery 
}
</script>

我不想使用$()。click或$()。 jquery,但使用上面描述的方法。

I want to do this without the use of $().click or $().live of jquery but with the method described above.

推荐答案

传入这个 in内联点击处理程序

pass in this in the inline click handler

<a href="123.com" onclick="click123(this);">link</a>

或者在函数中使用 event.target (根据 W3C DOM Level 2事件模型

or use event.target in the function (according to the W3C DOM Level 2 Event model)

function click123(event)
{
    var a = event.target;
}

当然, IE是不同的,所以处理这个问题的香草JavaScript方式是

But of course, IE is different, so the vanilla JavaScript way of handling this is

function doSomething(e) {
    var targ;
    if (!e) var e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;
}

或更少详细信息

or less verbose

function doSomething(e) {

    e = e || window.event;
    var targ = e.target || e.srcElement;
    if (targ.nodeType == 3) targ = targ.parentNode; // defeat Safari bug
}

其中 e 是传递给IE以外浏览器的函数的事件对象

where e is the event object that is passed to the function in browsers other than IE.

如果你尽管我使用jQuery,但我会强烈鼓励不显眼的JavaScript,并使用jQuery将事件处理程序绑定到元素。

If you're using jQuery though, I would strongly encourage unobtrusive JavaScript and use jQuery to bind event handlers to elements.

这篇关于如何获得onclick调用对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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