如何在锚点标记中以编程方式调用onclick()事件,同时在onclick函数中保留“this”引用? [英] How can I programmatically invoke an onclick() event from a anchor tag while keeping the ‘this’ reference in the onclick function?

查看:70
本文介绍了如何在锚点标记中以编程方式调用onclick()事件,同时在onclick函数中保留“this”引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以以编程方式为锚标记调用onClick-event,同时保持对锚的'this'引用?

以下不起作用...(至少不在Firefox中:document.getElementById('linkid')。click()不是函数)

The following doesn't work... (at least not in Firefox: document.getElementById('linkid').click() is not a function)

<script type="text/javascript">
    function doOnClick() {
        document.getElementById('linkid').click();
        //Should alert('/testlocation');
    }
</script>
<a id="linkid" href="/testlocation" onclick="alert(this.href);">Testlink</a>


推荐答案

你需要 apply 上下文中的事件处理程序那个元素:

You need to apply the event handler in the context of that element:

var elem = document.getElementById("linkid");
if (typeof elem.onclick == "function") {
    elem.onclick.apply(elem);
}

否则会引用上面代码执行的上下文。

Otherwise this would reference the context the above code is executed in.

这篇关于如何在锚点标记中以编程方式调用onclick()事件,同时在onclick函数中保留“this”引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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