jquery.each 函数是否有可能不破坏“this"变量? [英] Is it possible for jquery.each function not to clobber the 'this' variable?
问题描述
所以如果变量this"当前设置为一个对象,
So if the variable "this" is currently set to an object,
{ name: "The old this" }
下面的代码会在循环中改变它
the following code will change it in the loop
var array = [1, 2, 3];
$.each(array,
function(i, e){
alert(this.name);
}
);
不会找到this.name,而是在循环执行期间将变量this"设置为与e"相同
this.name wont be found, instead the variable "this" is set to the same as 'e' during the loop execution
jquery 是否可以不破坏 $.each 循环上的 this 变量?
Is it possible to have jquery not clobber the this variable on $.each loops?
推荐答案
如果你使用原生的 .forEach
而不是 $.each
,你可以设置 this
通过发送第二个参数的回调值...
If you use the native .forEach
instead of $.each
, you can set the this
value for the callback by sending a second argument...
array.forEach(function(e, i) {
alert(this.name);
}, this);
您需要修补旧版浏览器,包括 IE8...
You'll need to patch older browsers, including IE8...
- 兼容性补丁来自 MDN
- Compatibility patch from MDN
或者你可以使用 jQuery 的 $.proxy
返回一个具有所需 this
值的函数...
Or you can use jQuery's $.proxy
to return a function with the desired this
value...
$.each(array, $.proxy(function(i, e) {
alert(this.name);
}, this) );
这篇关于jquery.each 函数是否有可能不破坏“this"变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!