matriz de imágenes de Javascript [duplicado]

needing some help. I have two divs that I need to fill with images. The images can't be random as div 1's image needs to correspond to div 2's. I've been playing around and have managed to get the javascript working to this point. The problem is I need the script to write to the div backgrounds rather than fill the div with an image.

var random = Math.random();
function random_imglink(arr){
var ry = Math.floor(random*arr.length);
'<img src="'+arr[ry]+'" border=0 class="two">'
var myimages = [
"img1.jpg", "img2.jpg","img3.jpg"
myimagesA = [

<div><script>random_imglink(myimages);</script> </div>


preguntado el 28 de agosto de 12 a las 09:08

Pretty much 90% of text and title of this post have nothing to do with real question, I'd suggest editing it and throwing out irrelevant parts. -

3 Respuestas

Your code needed quite an overhaul. This is what it should look like after being fixed:

<div id='a'>A</div>

<div id='b'>B</div>​
var random = Math.random();
function random_imglink(arr, id){
    var ry = Math.floor(random*arr.length);
    document.getElementById(id).style.backgroundImage = "url('" + arr[ry] + "')";
var myimages = [
    myimagesA = [""];

random_imglink(myimages, 'a');
random_imglink(myimages, 'b');


Respondido 28 ago 12, 09:08

Thank you Amaan!! This is just what I needed - Tallulah

To set an image as the background of an element you can use this:

document.getElementById("myDivId").style.backgroundImage = "url(/path/to/img)";

In your code, you could do it something like:

var random = Math.random();

function random_imglink(divId, arr){
    var ry = Math.floor(random*arr.length);
    document.getElementById(divId).style.backgroundImage = "url(" + arr[ry] + ")";

var myimages = ["img1.jpg", "img2.jpg","img3.jpg"],
   myimagesA = ["img1b.jpg","img2b.jpg","img3b.jpg"];

random_imglink("firstDiv", myimages);
random_imglink("secondDiv", myimagesA);


<div id="firstDiv"></div>
<div id="secondDiv"></div> 

Respondido 28 ago 12, 09:08

Smallest possible change of the current code; make the function write a div tag with a style attribute instead of an image tag:

document.write('<div style="background:url('+arr[ry]+')">');

Put the script where you want the start tag:

<script>random_imglink(myimages);</script> </div>

Respondido 28 ago 12, 09:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.