如何显示从列表生成的随机项?

时间:2018-03-28 20:15:56

标签: javascript html

一旦生成“randomSong”,我希望它在下面显示如下句子:

  

在我们的聊天论坛中使用!code(我随机生成的代码)命令兑换保费。

function findSong() {
  var song = ["xikskx", "iwnujk", "ldilxb", "hgbhrw", "ijkczb"];

  var random = Math.floor(Math.random() * (song.length - 1));

  document.getElementById("randomSong").setAttribute("value", song[random]);
}
<div>
  <button onclick="findSong();" type="randomSong">Generate Premium Code</button>
  <input "RandomCode" id="randomSong">
</div>

1 个答案:

答案 0 :(得分:0)

您可以在html代码中添加<p>元素,用于显示新生成的文本。

<div>
    <button onclick="findSong();" type="randomSong">Generate Premium Code</button>
    <input "RandomCode" id="randomSong">

    <!-- new code -->
    <p id="text"></p> 
</div> 

然后点击这样填充它。

function findSong() {
    var song = ["xikskx", "iwnujk", "ldilxb", "hgbhrw", "ijkczb"];

    var random = Math.floor(Math.random() * (song.length - 1));

    document.getElementById("randomSong").setAttribute("value", song[random]);

    // new code
    var premium = document.getElementById('text');
    premium.textContent = 'Use the code ' + song[random] + ' command in our chat forums to redeem premium.';
}

小提琴:https://jsfiddle.net/LLu75ksf/5/