move event handler with jQuery
I have an issue which is driving me crazy and as a last resort I am placing a question here.
I want to move the onclick event from an element to the onfocus event of the same element and I am using the following code:
$("#theElement").bind("focus", {}, $("#theElement").data("events").click);
$("#theElement").unbind("click");
Maybe you have guess it. IT DOES NOT WORK.
How do I make this work? I am getting a "fn.apply is not a function" message in the following piece of code from jquery 1.3.2:
proxy: function( fn, proxy ){
proxy = proxy || function(){ return fn.apply(this, arguments); };
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || proxy.guid || this.guid++;
// So proxy can be declared as an argum开发者_开发百科ent
return proxy;
}
EDIT: I'm sorry, I should have mentioned. This comes from a plugin which does some stuff when clicking an element. I want to make the same thing when the element gets focus not when it is cliked so the simplest solution I thought off was this since I can't modify the code for the plugin.
EDIT: Found the problem. It is similar to what @sje397 posted in his answer, not
$('#theElement').data('events').click[0]
but
$('#theElement').data('events').click[3]
For some reason, even if only one event is registered the thing ends up as 3 (the guid in that piece of code from jquery).
I would suggest naming the event handler in the first place, like
$('#theElement').click(function myHandler() {
//...
});
Then, you can do
$("#theElement").bind("focus", {}, myHandler);
$("#theElement").unbind("click");
This should make it more readable, as well as fixing the bug.
If you can't, then you can do:
// assuming yours is the first handler
var myHandler = $('#theElement').data('events').click[0];
$("#theElement").bind("focus", {}, myHandler);
$("#theElement").unbind("click");
Also not that in jQuery 1.4.3+, the key was changed to __events__
. See this answer.
I found out that jQuery adds the event to an element by using .data()
, so you could do something like this to retrieve the event handler:
$(el).data().events.click[0].handler
This is not an elegant solution, but if you cannot change anything to the click handler itself, this would be the only solution.
I'm not 100% clear what it is exactly that you want to do. Do you want to bind a focus AND a click event to the same element?
$("#theElement").bind("focus click", function(){
//do stuff
$(this).unbind('focus click');
});
edit: given your clarification - you want to fake the 'click' event on focus...
$("#theElement").bind("focus", function(){
$(this).trigger('click');
});
http://api.jquery.com/trigger/
精彩评论