views:

51

answers:

2

Code snippet as follows:

$(this).parents('td:first').next().find('option').customizeMenu('myMenu2');

This works,but :

var listener = function(){
 $(this).parents('td:first').next().find('option').customizeMenu('myMenu2');
};
listener();

is not working,why and how to fix it?

+6  A: 

'this' does not point to the same object when put in a function, it points to the current function (in your case 'listener'). Take it as a parameter instead, if that is an option (it depends on how you call your function).

var listener = function(obj){
 $(obj).parents('td:first').next().find('option').customizeMenu('myMenu2');
};

listener(this);
Björn
+1 for being 7 seconds quicker.
Kobi
:P Now I feel that I have to upvote you (and I will). ;)
Björn
+3  A: 

this is the function. Try:

var listener = function(element){
  $(element).parents('td:first').next().find('option').customizeMenu('myMenu2');
};
listener(this);
Kobi