![](/img/trans.png)
[英]Using for-in loop to iterate localStorage returns spurious entries
[英]Cannot iterate using for-in javascript
我正在嘗試使用for...in
循環將圖像顯示為我的圖庫的縮略圖,但是它只能顯示一個圖像。 我仍然是javascript的初學者,因此我對for循環的理解仍然不好。 我哪里做錯了?
樣本數組:
["http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png",
"http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png"]
for...in
循環中:
for(var thumb in thumbnails) {
$('.thumbnail img').attr({"src":[thumbnails[thumb]]});
}
實際上,您的循環非常好。 您確實遍歷了數組中的所有URL,但是對於每個URL,您都將其設置為同一縮略圖img
src
,每次都有效地覆蓋了它。
很難幫助您解決它,因為我不知道您的確切布局和要求,但是實際上您要么需要為縮略圖創建一組img
(而不是僅一個img
,現在看來就是這種情況) ),並按順序設置其src
,或者每次創建全新的img
並將其附加到某個父容器中,如下所示:
for(var thumb in thumbnails) {
$(<some container>).append($('<img>').attr({"src":[thumbnails[thumb]]}));
}
您不應該使用for .. in
來遍歷數組。 為什么?
請改用Array.prototype.forEach
。
另外,如果要使用jQuery創建元素,請使用另一種語法:
thumbnails.forEach(function(thumb) {
$("<img/>").attr('src', thumb).appendTo(container);
});
工作示例:
var thumbnails = [ 'https://blog.stackoverflow.com/images/wordpress/stackoverflow-logo-alt2-300.png', 'http://letscode.ghost.io/content/images/2015/09/stackoverflow.png', 'http://i.stack.imgur.com/kq8EX.png']; thumbnails.forEach(function(thumb) { $("<img/>").attr('src', thumb).appendTo('body'); });
img { height: 100px; width: auto; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.