我正在尝试从数组中检索图像,并在加载时随机填充每个项目的src
,但是图像返回为[object Object]
。
$(document).ready(function() {
var imagesArray = [{
id: "one",
src: "https://cdn.shopify.com/s/files/1/1450/6394/products/MCS10014LS_MOCK_UP_1024x1024.png?v=1545018000"
},
{
id: "two",
src: "https://assets.bigcartel.com/product_images/191933374/tank_bikes_not_war_american_apparel__tri-oatmeal_mockup.png"
},
{
id: "three",
src: "https://cdn.shopify.com/s/files/1/0617/7613/products/Allday-No-Saint-Hockey-Jersey-MOCK_1024x1024.png?v=1492726972"
}
];
$(".item").each(function() {
var randomImage =
imagesArray[Math.floor(Math.random() * imagesArray.length)];
$(this)
.find("img")
.attr("src", randomImage);
});
});
.item {
border: 2px solid;
height: 40px;
width: 40px
}
.item img {
max-height: 40px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="item">
<img src="https://www.emergerstrategies.com/wp-content/themes/cannyon_/media/_frontend/img/grid-no-image.png">
</div>
<div class="item">
<img src="https://www.emergerstrategies.com/wp-content/themes/cannyon_/media/_frontend/img/grid-no-image.png">
</div>
<div class="item">
<img src="https://www.emergerstrategies.com/wp-content/themes/cannyon_/media/_frontend/img/grid-no-image.png">
</div>
答案 0 :(得分:1)
对图像数组进行采样的结果是一个像这样的对象:
{
id: "one",
src: "https://cdn.shopify.com/s/files/1/1450/6394/products/MCS10014LS_MOCK_UP_1024x1024.png?v=1545018000"
}
您只需要从中引用正确的属性即可
.attr("src", randomImage.src);
您看到[object Object]
是因为属性值在分配时被强制转换为字符串,并且object.toString()
是字符串文字"[object Object]"
:
({id: "one", src: "foo"}).toString()
"[object Object]"