问题描述
我可以通过调用
$('#id')来设置onclick处理程序。 {
console.log('click!');
});
同样使用jQuery,我如何获得对当前处理click()事件?
原因是我有另一个对象,并且想要将其点击处理程序设置为与#id相同的一个。
更新
感谢您的所有建议。问题是我不知道哪个函数正在处理点击。跟踪它会将状态添加到已经很复杂的模板编辑系统中。 jQuery的 .click (函数)
方法将函数添加到在click事件中执行的队列中〜所以实际上拉出了给定函数的引用可能会比你期望的要多毛。
var clicky = function(){/ * do stuff * /};
$('#id')。click(clicky);
//用clicky
做其他事情
更新
如果你真的需要把它弄出来,试试这个:
jQuery._data(document.getElementById ('id'))。events.click [0] .handler
取决于您的jQuery版本这可能会或可能不会工作〜尝试玩弄
jQuery._data(document.getElementById('id'))
并且看看您得到了什么。
得到来自这部分来源的想法:
I can set the onclick handler using jQuery by calling
$('#id').click(function(){
console.log('click!');
});
Also using jQuery, how can I get a reference to the function which is currently handling the click() event?
The reason is that I have another object and want to set its click handler to the same one as #id.
Update
Thank you for all the suggestions. The problem is that I do not know which function is currently handling the clicks. Keeping track of it would add state to an already complicated template-editing system.
jQuery's .click(function)
method adds the function to a queue that is executed on the click event~
So actually pulling out a reference to the given function would probably be hairy-er than you expect.
As noted by others, it would be better to pass in a reference to the function; and then you already have the reference you need.
var clicky = function () { /* do stuff */ };
$('#id').click(clicky);
// Do other stuff with clicky
Update
If you really really need to get it out, try this:
jQuery._data(document.getElementById('id')).events.click[0].handler
Depending on your version of jQuery that may or may not work~ Try playing around with
jQuery._data(document.getElementById('id'))
and see what you get.
Got the idea from this section of the source:
https://github.com/jquery/jquery/blob/master/src/event.js#LC36
这篇关于使用jQuery获取当前事件处理程序的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!