【问题标题】:javascript scope issuejavascript范围问题
【发布时间】:2009-12-07 09:56:12
【问题描述】:
代码sn-p如下:
$(this).parents('td:first').next().find('option').customizeMenu('myMenu2');
这可行,但是:
var listener = function(){
$(this).parents('td:first').next().find('option').customizeMenu('myMenu2');
};
listener();
不工作,为什么以及如何解决?
【问题讨论】:
标签:
javascript
jquery
scope
【解决方案1】:
'this' 在放入函数时并不指向同一个对象,它指向当前函数(在您的情况下为“侦听器”)。如果可以选择,请将其作为参数(这取决于您调用函数的方式)。
var listener = function(obj){
$(obj).parents('td:first').next().find('option').customizeMenu('myMenu2');
};
listener(this);
【解决方案2】:
this 是函数。试试:
var listener = function(element){
$(element).parents('td:first').next().find('option').customizeMenu('myMenu2');
};
listener(this);