Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
889 views
in Technique[技术] by (71.8m points)

html - Javascript random image on click button

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

<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()"/>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to add quotes in this line and close the if statement:

<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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...