最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Javascript random image on click button - Stack Overflow

programmeradmin0浏览0评论

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()"/>

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()"/>
Share Improve this question edited Jul 29, 2013 at 20:13 putvande 15.2k3 gold badges36 silver badges51 bronze badges asked Jul 29, 2013 at 20:04 AlexanderAlexander 4,2193 gold badges22 silver badges42 bronze badges 3
  • 1 You need to add quotes around what you're writing: document.write('<img class="who" src="'+myImages1[rnd])+'">); and you never finished your img tag. – tymeJV Commented Jul 29, 2013 at 20:06
  • 1 Your array should be 0,1,2 not 1,2,3. You're missing the closing paren on if (rnd == 0 - that line goes away anyway. You can't use document.write after the page is loaded - it will kill the whole page - you need to put the value into a container. You're missing the quotes and closing angle-bracket on the img tag that you're writing. – Joe Enos Commented Jul 29, 2013 at 20:07
  • Doesn't your "random generator" mostly be 1? Just wondering if you should write a more random number generating logic – theshadowmonkey Commented Jul 29, 2013 at 20:20
Add a ment  | 

7 Answers 7

Reset to default 1

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>

You forgot a ) in your if statement and on your document.write you missed ' and closing the <img> tag. Check here:

if (rnd == 0) {
        rnd = 1;
    }

document.write('<img class="who" src="' + myImages1[rnd] + '"/>');

Make sure to keep track of all your closing brackets and parenthesis.

This code will work for you:

<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;
      }
      html_code = '<img class="who" src="' + myImages1[rnd] + '" />";
      document.write(html_code);
    }
</script>

Also if I were you, I would point to a more specific point in your DOM document.. You could use a very simple jQuery script like this if you want: $("#testing").html(html_code); instead of your document.write()

To APPEND something in your page to an element in the HTML, use

.append

rather than the "write" function, as .append will actually APPEND content to a specified element, rather than all over your whole DOCUMENT.

So, in your HTML, you should create a DIV with ID "our_div"

<html>
<head></head>
<body>
<!-- Text will be appended to this DIV via JS -->
<div id="the_div">Hello, </div>
</body>
</html>

Use something like this:

function add_text() {
  $("#the_div").append("World"); // appends text "World" to the end of that div.
}

Now, inside your HTML, you should have a button that calls the function "add_text()".

<button id="the_button" onClick="add_text();">Click Here to Add Text</button>

Now then!

When a user clicks the button, it will append the text "World" to the DIV with ID "the_div..." THUS, we have...

Hello, World

Here's the entire code:

<html>
<head>
<script type="text/javascript">
function add_text() {
  $("#the_div").append("World");
}
</script>
</head>
<body>
<div id="the_div">
Hello, 
</div>
<button id="the_button" onClick="add_text();">Click!</button>
</body>
</html>

Try using

.html

to REPLACE something... For example, I use a Dice Roll Function in a game I have developed. When a player rolls the dice...

$("#results").append(Math.floor(Math.rand()*6));

gives us something like this...

(every roll)

results: 142563342515246422

and if I use .html...

$("#results").html(Math.floor(Math.rand()*6));

we are left with something more like this

(first roll)

results: 5

(second roll)

results: 2

(third roll)

results: 6

And so on!

The HTML you are writing to your document is inplete.

You need something like:

document.write("<img class='who' src='" + myImages1[rnd] + "'>");

I would also caution that document.write is not normally a preferred method of adding elements to the page, but it seems that this is more a learning example than a real world example.

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;

What was I thinking assigning an array to [1] and then doing an if check? I'll never know.

This is the best way I can think of, the reason I prefer this, is because instead of changing the whole page, it just changes the src in the img tag.

Here's the code:

Script

function imgchange() {

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.getElementById("gen-img").src = myImages1[rnd];

}

Html

<p><img id="gen-img" src="img/who/1.jpg"></p>
<p><input type="button" value="Random" onclick="imgchange();" /></p>

What I do however, is I have a blank png file with nothing in it, and I set that as the default src for my image. But you can do as you please.

发布评论

评论列表(0)

  1. 暂无评论