简体   繁体   English

如何在jQuery每个循环中保存对上下文的更改?

[英]How can I save changes to the context in a jQuery each loop?

I have the following code, which preprocesses some response data from an AJAX call before displaying it (the displaying part is not shown). 我有以下代码,该代码在显示AJAX调用之前会对其进行一些预处理(未显示显示部分)。 In particular, it sets the src attribute of the image in each li element of the response. 特别是,它在响应的每个li元素中设置图像的src属性。

$(response.items).filter('li').each(function(i){

  $('img', this).attr('src', 'images/Picture.jpg');
  if (i==0){
    console.log(this);
    console.log(response.items);
  }

});

The output of console.log(this) shows that the src attribute gets set correctly in the context represented by this , but the output of console.log(response.items) shows that response.items is unchanged. console.log(this)的输出显示src属性在this表示的上下文中正确设置,但是console.log(response.items)的输出显示response.items不变。

Is there a (preferably non-hacky) way to persist all changes to the li elements to response.items ? 有没有一种(最好是非hacky)的方法来将对li元素的所有更改持久化到response.items

I think the problem here is that you're using the filter method. 我认为这里的问题是您正在使用filter方法。 Filter (and also map ) don't modify the original array, they essentially make a copy of it. Filter (也map )不修改原始数组,它们实质上是复制它的副本。 So if you would check the return value of this whole code block like this: 因此,如果您要像这样检查整个代码块的返回值:

var processed = $(response.items).filter('li').each(function(i){

  $('img', this).attr('src', 'images/Picture.jpg');
  if (i==0){
    console.log(this);
  }

});
console.log(processed);

It should properly show the changed values. 它应该正确显示更改的值。 Depending on what you want to do you could also use a map method after the each. 根据您要执行的操作,您还可以在每个方法之后使用map方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM