【发布时间】:2016-11-12 21:26:17
【问题描述】:
我正在尝试使用 button 对 id="demo" 的内容进行排序,但每次单击按钮时,我什么也得不到。
单击按钮后,我希望 select() 能够读取 id="demo" 的内容(一旦输出随机数)并将它们排序/转储到 id="demo2" 中。
我认为正在发生的事情是 select() 正在将 var arr 读取为空白数组,而不是具有随机数字分类的数组(因为它位于 first() 的末尾)
<input id="input1" type="number" min="10" max="100" onchange="first(); sortButton();">
<p id="demo"></p>
<!-- button appears here, once a value is entered into the input field -->
<p id="buttons1" onclick="select();"></p>
<p id="demo2"></p>
<script>
// once input1 value changes this outputs a random value less than N (value of input1) N times, then dumps out the random numbers in id="demo"
function first() {
var N = document.getElementById("input1").value;
var arr = [];
while(arr.length < N)
{var randomnumber = Math.ceil(Math.random()*N);
arr[arr.length] = randomnumber;}
document.getElementById("demo").innerHTML = arr;}
// Once input1 value changes, this buttons appears in id="buttons"
function sortButton() {document.getElementById("buttons1").innerHTML =
'<button type="button" onclick="select();">Select Sort</button>';}
// meant to sort the random numbers in id="demo" once the button is clicked
function select() {
document.getElementById("demo2").innerHTML = arr.sort(function(a,b){return a - b});}
</script>
【问题讨论】:
-
您的代码格式不正确吗?我几乎会认为
select是first函数的一部分,当您运行代码时会发生变化,调试器中是否有任何错误?单击按钮时是否出现错误?
标签: javascript arrays function sorting