简体   繁体   中英

displaying images from a function that returns an array in javascript

I have a function that randomizes an array of images and returns an array with the random images after they are displayed.

<script type = "text/javascript">
var images = new Array('0.jpg', '1.jpg' , '2.jpg'), result=[] ;
Array.prototype.random = function () {
    var that = this.slice();
    var length=images.length;
    var rand;
    for(i=0; i<=4;i++)
    {
        rand=Math.floor(Math.random()*(length));
        result.push(images[rand]);
    }
    return result;
} 

//document.write(images.random()); when I do this I get the array with the images but I want to display them using something like document.write('<img src="images/'+images.random()+'" width = \\"\\" height = \\"\\"/>'); \\but thats not working..any ideas

Your problem in whenever you do document.write it wipes all the DOM out. the better solution is to create your images using document.createElement and then append them to the body or to any other container you want.

first to make your code clear create a function like this:

function createImage(imgname){
    var img = document.createElement("img");
    img.src = "images/" + imgname;
    return img;
}

then do this:

images.random().forEach(function(imgname){
    document.body.appendChild(createImage(imgname));
});

I used some of the help provided by some of you and here is what i got. so this code takes an array of images, randomizes them, displays them

<script type="text/javascript">
var images=new Array('g.jpg','f.jpg','f.jpg')
var re=[];
var length=images.length;
var entered=document.getElementById('images');
for(var f=0; f<4; f++){
var ran=Math.floor(Math.random()*(length));
var imge=document.createElement("img";
image.src="images/" + images[ran];
entered.appendchild(image);
</script)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM