[英]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.