简体   繁体   中英

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). In particular, it sets the src attribute of the image in each li element of the response.

$(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.

Is there a (preferably non-hacky) way to persist all changes to the li elements to response.items ?

I think the problem here is that you're using the filter method. Filter (and also map ) don't modify the original array, they essentially make a copy of it. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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