【发布时间】:2015-08-23 04:46:36
【问题描述】:
嗨_我正在尝试让一个随机数出现在一个 div 的 img src= 地址内,这样每次加载 div 时都会生成一个随机图像。
我有 10 张图片,它们的目录地址是:
"pictures/number1.jpg"
"pictures/number2.jpg"
"pictures/number3.jpg"
................
"pictures/number10.jpg"
我可以使用以下 Javascript 随机选择其中之一:
var num = Math.floor(Math.random() * 10 + 1);
img.src = "pictures/number" +num +".jpg";
这会生成一个介于 1 和 10 之间的随机数,并将其放在地址中以定位图像。
当 img.src 在 Javascript 文件中使用时,这非常有效,但我想知道当 img src= 是 HTML 页面的一部分时是否可以使用此方法。我正在尝试对以下 HTML 代码应用类似的过程:
<script>
var num = Math.floor(Math.random() * 10 + 1);
randomimage = "pictures/number" +num +".jpg";
</script>
<div id="JohnDIV" align="center"> <img src=randomimage alt="If you can see this, then the image didn't load properly" class="myclass1" /> </div>
<div id="JackDIV" align="center"> <img src=randomimage alt="If you can see this, then the image didn't load properly" class="myclass1" /> </div>
<div id="JaneDIV" align="center"> <img src=randomimage alt="If you can see this, then the image didn't load properly" class="myclass1 /> </div>
这不起作用,它只是向我显示alt= 消息。我不确定我是否正确定义了randomimage。
我真的很困惑如何以正确的方式去做这件事,任何帮助将不胜感激!
提前致谢!
【问题讨论】:
-
看来您正在尝试诸如服务器端代码之类的东西……例如 php 或 asp。 Javascript 不能这样工作。
-
您必须在脚本中遍历the elements with the class,然后为该循环中的图像设置
imgs。
标签: javascript jquery html css random