我正在尝试使用JavaScript,我想显示一串生成的随机数字,这些数字存储在html中的数组中。
我目前只能使用.toString()
在底部显示一个值我想要的是,每次按下生成时,新值都会添加到数组中,而完整数组将作为列表打印在下面。
<!DOCTYPE html>
<html>
<body bgcolor="#000000">
<font size="30" color="orange">Hex Value :- <strong><p align="center"><font size="80" color="orange"><span id="first"></span></p></strong>
<p align="center"><button onclick="incremente()">Generate</button></p>
<font size="3" color="green">Values generated this session:- <strong><p align="center"><font size="40" color="green"><span id="second"></span></p></strong>
<script>
function incremente() {
var CHARS = new Array();
rand = Math.floor(Math.random() * (17 - 0)) + 0;
randy = Math.round(rand);
$outChar = randy;
$first = $outChar;
var place1=document.getElementById('first');
place1.innerHTML=$first;
CHARS.push($first);
$second = CHARS.toString();
for (i=0;i<CHARS.length;i++)
{
var place2=document.getElementById('second');
place2.innerHTML=$second;
}
}
</script>
</body>
</html>
答案 0 :(得分:0)
将数组移到函数上方,使其变为全局。
检查代码。
<body bgcolor="#000000">
<font size="30" color="orange">Hex Value :- <strong><p align="center"><font size="80" color="orange"><span id="first"></span></p></strong>
<p align="center"><button onclick="incremente()">Generate</button></p>
<font size="3" color="green">Values generated this session:- <strong><p align="center"><font size="40" color="green"><span id="second"></span></p></strong>
<script>
var CHARS = new Array();//moved above the function such that it becomes global.
function incremente() {
rand = Math.floor(Math.random() * (17 - 0)) + 0;
randy = Math.round(rand);
$outChar = randy;
$first = $outChar;
var place1=document.getElementById('first');
place1.innerHTML=$first;
CHARS.push($first);
$second = CHARS.toString();
for (i=0;i<CHARS.length;i++)
{
var place2=document.getElementById('second');
place2.innerHTML=$second;
}
}
</script>
</body>
</html>
&#13;
Plunk here,您可以在js中使用您的代码