如何获得绑定到onclick属性的函数? [英] How can I get the function bound to an onclick attribute?

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

问题描述

我在html中的onclick事件上绑定了一个函数,如下所示:

I've got a function bound to the onclick event in the html, like so:

<script>
    function f1(){ alert('hello world'); };
</script>

<a onclick="f1()">test</a>

我想使用该功能执行某项操作,例如将其绑定到另一个事件.我在jQuery中尝试过:

I'd like to do something with that function, like bind it to another event. I tried this in jQuery:

var defaultFunction = $('a').attr('onclick');

但是defaultFunction被定义为字符串而不是函数本身.我可以用eval(defaultFunction)进行评估,但这使我感到肮脏.有没有办法我可以访问函数本身而不是字符串?

but defaultFunction is defined as a string rather than the function itself. I can evaluate it with eval(defaultFunction), but that makes me feel dirty. Is there a way I can access the function itself, rather than the string?

即我希望能够调用defaultFunction()并执行绑定到a元素的默认onclick行为. (在这种情况下,请致电f1().)

i.e. I'd like to be able to call defaultFunction() and do whatever the default onclick behavior bound to the a element is. (In this case, call f1()).

这里是一个尝试这样做的小提琴,但失败了.

推荐答案

它只是onclick属性,不需要jQuery:

It's just onclick attribute, no jQuery required:

<script>
    function f1(){ alert('hello world'); };
</script>

<a onclick="f1()" id="aa">test</a>
<a id="bb">test2</a>

<script>
    bb.onclick = aa.onclick;
    // or
    bb.onclick = function (){ alert('hello bb'); };   
</script>

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

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