问题描述
我一直在关注如何通过在Javascript中设置数组来随机化图像的一些教程。它不工作 - 图像本身没有出现,甚至没有任何错误。
I've been following some tutorials on how to randomize an image by setting up an array in Javascript. It's not working - the image itself is not appearing, not even any error.
JavaScript
JavaScript
<script type="text/javascript">
function randomImg1(){
var myImages1 = new Array ();
myImages1[1] = "img/who/1.jpg";
myImages1[2] = "img/who/2.jpg";
myImages1[3] = "img/who/3.jpg";
var rnd = Math.floor(Math.random() * myImages1.length);
if(rnd == 0{
rnd = 1;
}
document.write(<img class="who" src="'+myImages1[rnd]);
}
</script>
我的按钮看起来像这样
and my button looks like this
<input class="randombutton" style="float: left;" type="button" value="Randomize" onclick="randomImg1()"/>
推荐答案
哦这是令人尴尬的,疯狂的你可以在3年内学到多少,我认为这样做的最佳方式是下面的(假设没有文件夹结构模式),没有测试但应该工作。 >
Oh man, this is embarrassing. Crazy how much you can learn in 3 years. I think the most optimal way of doing this would be the following (assuming there is no folder structure pattern). Haven't tested but should work.
var images = ["img/who/1.jpg","img/who/2.jpg","img/who/3.jpg"];
function getRandomImage(){
var rnd = Math.floor(Math.random() * images.length);
return images[rnd];
}
function changeImage(){
var img = document.querySelector("#myImg");
img.src = getRandomImage();
}
function init(){
var el = document.querySelector(".myClass");
el.onclick = changeImage;
}
window.onload = init;
我在想为数组赋值 [1]
,然后做一个 if if
check?我永远不会知道。
What was I thinking assigning an array to [1]
and then doing an if
check? I'll never know.
这篇关于单击按钮上的Javascript随机图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!