jquery.each函数是否有可能不破坏'this'变量?

时间:2012-02-11 20:58:52

标签: javascript jquery

因此,如果变量“this”当前设置为对象,

{ name: "The old this" }

以下代码将在循环中更改它

var array = [1, 2, 3];
$.each(array,
  function(i, e){
    alert(this.name);
  }
);
找不到this.name,而是在循环执行期间将变量“this”设置为与'e'相同

是否有可能让jquery不破坏$ .each循环中的这个变量?

4 个答案:

答案 0 :(得分:6)

如果您使用原生.forEach代替$.each,则可以通过发送第二个参数来设置回调的this值。

array.forEach(function(e, i) {
    alert(this.name);
}, this);

您需要修补旧浏览器,包括IE8 ......


或者您可以使用jQuery的$.proxy返回具有所需this值的函数...

$.each(array, $.proxy(function(i, e) {
    alert(this.name);
}, this) );

答案 1 :(得分:3)

您可以将this存储到本地变量中,然后在each循环中使用它。试试这个。

var data = this;//where this = { name: "The old this" }
var array = [1, 2, 3];
$.each(array,
  function(i, e){
    alert(data.name);
  }
);

内部each循环this将指向数组的每个元素。

答案 2 :(得分:1)

为了完整性,使用原生JS和Function.prototype.bind类似的另一个解决方案是使用// wrapper function to set `this` scope. (function() { $.each([1, 2, 3], (function(i, e) { alert(this.name); }).bind(this)); }).call({ name: "The old this" });

Image img = picturebox1.Image();
byte[] arr;
ImageConverter converter = new ImageConverter();
arr=(byte[])converter.ConvertTo(img, typeof(byte[]));

command.CommandText = "INSERT INTO ImagesTable (Image) VALUES('" + arr + "')";
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();

答案 3 :(得分:0)

如果您不希望更改this,那么只需使用正常的for循环:

var array = [1, 2, 3];
for (var i = 0; i < array.length; i++) {
    // operate on array[i]
    alert(this.name);
}

你无法改变jQuery .each()的行为。它被编码为设置this.each()迭代器意味着方便 - 因此你应该只在它比for循环更方便的时候使用它,而不是在它导致更多麻烦时使用它。

其他答案向您展示了如何将this保存到另一个变量。