具有字幕的对象随机图像生成器阵列

时间:2018-01-20 05:07:40

标签: javascript arrays object random

我正在尝试构建一个随机图像生成器,该生成器还有两个与其关联的其他字段或标题,显示在页面上。我认为解决方案是创建一个对象数组,但我对对象和类非常生疏,所以我不确定我是否正确构建它。这是html:

<div class="col-md-6 col-lg-4 col-sm-12">
    <img id="winnerImage" src="http://placehold.it/1500x1200" alt="Winners at Rhythm City Casino Resort&reg;" width="1500" height="1200" class="img-thumbnail img-fluid">
</div>
<div class="col-md-6 col-lg-8 col-sm-12">
    <h2 class="display-3" id="winnerHeader">Another Big Winner at Rhythm City!</h2>
    <h3 id="winnerCaption">Debbie R. &bull; $5,000&nbsp;Winner.</h3>
    <p class="text-center"><a href="winners.html" class="btn btn-primary">View Winners Gallery</a></p>
</div>

和我的脚本文件

window.onload = choosePic;

function BigWinner(source, name, amount) {
    this.source = source;
    this.name = name;
    this.amount = amount;
}

var winnersArray = new Array (
    BigWinner("JohnD_1280.40_DeWittIA_September2017.JPG", "John D.", "$1,280"),
    BigWinner("KaronB_13004.81_DavenportIA_September2017.JPG", "Karon B.", "$13,004"),
    BigWinner("KyleG_1742_NewBostonIL_September2017.JPG", "Kyle G.", "$1,742"),
    BigWinner("MarciaP_2000.40_LeClaireIA_November2017.JPG", "Marcia P.", "$2,000"),
    BigWinner("ShaneE_4164,76_CamancheIA_September2017.JPG", "Shane E.", "$4,164")
);

function choosePic() {
    randomNum = Math.floor((Math.random() * winnersArray.length));
    document.getElementById("winnerImage").src = "img/Casino/Winners/" + winnersArray[randomNum].source;
    document.getElementById("winnerCaption").innerHTML = winnersArray[randomNum].name + " &bull; " + winnersArray[randomNum].amount + " Winner";
}

1 个答案:

答案 0 :(得分:0)

有些事情,您的数组语法可以简化,并且在制作新的BigWinners时您需要使用new关键字。

var winnersArray = [
    new BigWinner("JohnD_1280.40_DeWittIA_September2017.JPG", "John D.", "$1,280"),
    new BigWinner("KaronB_13004.81_DavenportIA_September2017.JPG", "Karon B.", "$13,004"),
    new BigWinner("KyleG_1742_NewBostonIL_September2017.JPG", "Kyle G.", "$1,742"),
    new BigWinner("MarciaP_2000.40_LeClaireIA_November2017.JPG", "Marcia P.", "$2,000"),
    new BigWinner("ShaneE_4164,76_CamancheIA_September2017.JPG", "Shane E.", "$4,164")
];