I’m trying to attach a function directly to a change event in jQuery, but I can’t quite figure it out. I need to pass the element that has changed as a paramater to the function I’m invoking.
Something like this, ( but it doesn’t work ):
var fun = function( trigger ){
// do something
};
$( 'select' ).change( fun( $(this) ) );
The following works:
$( 'select' ).change( function(){
fun( $(this) );
});
I’ve also tried (just for the hell of it)
$( 'select' ).bind( 'change', fun( $(this) ) );
But it doesn’t work either.
Will do the trick. You will be able to access
thisinside thefunfunction.Here is an example:
Your second solution works because the anonymous function you are passing as the event handler is given access to the
thisvariable and you are then passing it to thefunfunction. Any function passed to a jQuery event handler will recieve thethisvariable that stores a reference to the DOM element that had the event fire on it.