开发者

javascript scope issue

开发者 https://www.devze.com 2022-12-13 14:51 出处:网络
开发者_JS百科Code snippet as follows: $(this).parents(\'td:first\').next().find(\'option\').customizeMenu(\'myMenu2\');

开发者_JS百科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?


'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);


this is the function. Try:

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

精彩评论

暂无评论...
验证码 换一张
取 消