如何在JavaScript onclick上显示不同的图像并在第3次或第4次单击上显示相同的图像

问题描述 投票:0回答:1

window.onload = choosePic;
var myPix = new Array("img1.jpg", "img2.jpg", "img3.jpg");

function choosePic() {
  var randomNum = Math.floor(Math.random() * myPix.length);
  document.getElementById("myPicture").src = myPix[randomNum];
  document.getElementById("myPicture2").src = myPix[randomNum];
  document.getElementById("myPicture3").src = myPix[randomNum];
}
<img src="img.jpg" width="100" height="100" id="myPicture" alt="some image" />
<img src="img.jpg" width="100" height="100" id="myPicture2" alt="some image" />
<img src="img.jpg" width="100" height="100" id="myPicture3" alt="some image" />
<button id="btn" onclick="choosePic()">Click Hear</button>

我想显示阵列中的3个不同图像。并在第4或第5次点击以显示相同的图片。

javascript arrays image button random
1个回答
0
投票

这样的事情?

let clickCount = 0;
function choosePic() {
  clickCount++;
  if (clickCount < 4) {
    var randomNum = Math.floor(Math.random() * myPix.length);
    document.getElementById("myPicture").src = myPix[randomNum];
    document.getElementById("myPicture2").src = myPix[randomNum];
    document.getElementById("myPicture3").src = myPix[randomNum];
  } else {
    // perform your "show the same pic" operation here
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.