我有一组图像。我想随机显示图像。在for-each循环中我正在调用图像。假设我有10条记录,因此应该从脚本旁边的给定图像集中随机显示10个图像。但问题是只显示一个图像,其余图像不可见。循环工作正常。 getElementById只能用于一次id吗?我需要帮助来解决这个问题以及我犯错的地方。
这是代码。
<script>
var myPix = new Array("/Contents/img/CarrerGuide/office-1.png",
"/Contents/img/CarrerGuide/office-2.png",
"/Contents/img/CarrerGuide/office-3.png",
"/Contents/img/CarrerGuide/office-4.png",
"/Contents/img/CarrerGuide/office-5.png",
"/Contents/img/CarrerGuide/office-6.png",
"/Contents/img/CarrerGuide/office-7.png",
"/Contents/img/CarrerGuide/office-8.png",
"/Contents/img/CarrerGuide/office-9.png",
"/Contents/img/CarrerGuide/office-10.png");
var randomNum = Math.floor(Math.random() * myPix.length);
document.getElementById("myPicture").src = myPix[randomNum];
</script>
@{ var counter = 1; }
<tr>
@foreach (var item in Model)
{
<td>
<img id="myPicture" name="myPicture" alt="some image" class="img-responsive">
item.jobPosition
</td>
if (counter % 3 == 0) //Display 3 courses at a row
{
@:</tr><tr>
}
counter++;
}
答案 0 :(得分:1)
您必须选择具有属性名称为
$('[name=\'myPicture\']')
的所有元素,并迭代它们以更改每个元素的src
。在您的示例中,您没有为每个元素获得randomNum
。另请注意,对于同一文档中的多个元素,您不应该具有相同的
is
!
var myPix = ["/Contents/img/CarrerGuide/office-1.png",
"/Contents/img/CarrerGuide/office-2.png",
"/Contents/img/CarrerGuide/office-3.png",
"/Contents/img/CarrerGuide/office-4.png",
"/Contents/img/CarrerGuide/office-5.png",
"/Contents/img/CarrerGuide/office-6.png",
"/Contents/img/CarrerGuide/office-7.png",
"/Contents/img/CarrerGuide/office-8.png",
"/Contents/img/CarrerGuide/office-9.png",
"/Contents/img/CarrerGuide/office-10.png"
];
$('[name=\'myPicture\']').each(function() {
var randomNum = Math.floor(Math.random() * myPix.length);
this.src = myPix[randomNum];
});