Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

131
Visualizações
Random amount of pictures when clicking a button

i have an assignment were i need to create a function that when i click a button it needs to generate a random amount of pictures

var addImgBtn = document.getElementById("add-img-btn");
var outputDiv = document.getElementById("output-div");

function addImg() {
  outputDiv.innerHTML = `
    <img src="img/mann.jpg"/>
  `;
}

function addRandomImg() {
  addImgBtn = Math.floor(Math.random() * 100 + 1);
}

addImgBtn.onclick = addImg;
<input id="add-img-btn" type="button" value="Legg til bilde" />
<div id="output-div"></div>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

At some point you need to do some iteration to build up the HTML that contains all of the images.

  1. Your onclick should be calling addRandomImg.

  2. You should be assigning the result of the randomiser to a new variable, not addImgBtn.

  3. Use a for...loop to iterate between 0 and rnd, and on each iteration push the image HTML into an array. Once all iterations are complete you can finally update outputDiv with that HTML making sure you join up the elements of the array into a string.

var addImgBtn = document.getElementById("add-img-btn");
var outputDiv = document.getElementById("output-div");

function addRandomImg() {
  const rnd = addImgBtn = Math.floor(Math.random() * 100 + 1);
  let html = [];
  for (let i = 0; i <= rnd; i++) {
    html.push('<img src="https://dummyimage.com/20x20/000/fff"/>');
  }
  outputDiv.innerHTML = html.join('');
}

addImgBtn.onclick = addRandomImg;
img { margin: 2px 2px; }
<input id="add-img-btn" type="button" value="Legg til bilde" />
<div id="output-div"></div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda