2016-11-12 6 views
0

id = "demo"の内容をボタンでソートしようとしていますが、ボタンをクリックするたびに何も得られません。配列のソートに伴うエラー

ボタンをクリックすると、id = "demo"(一度乱数が出力される)の内容を読み込み、id = "demo2"にソート/ダンプします。

<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> 
+0

だけではないことも、フォーマットあなたのコードですか?私は '' select'が 'first'関数の一部であると思います。コードを実行しているときに何か変わってしまいます。デバッガにエラーがありますか?ボタンをクリックするとエラーが表示されますか? – Icepickle

答えて

0
(それが最初の()の終わりであるとして)

何が起こっていると考えることは選択では、()ではなく数字のランダムな組み合わせを持つ配列よりも、空白の配列としてのvar ARRを読んでいます

関数の外でvar arr = []を宣言する必要があります。ここに働くプログラムがあります。それが役に立てば幸い:)

// 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" 
 
var arr = []; 
 

 
function first() { 
 
var N = document.getElementById("input1").value; 
 
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}); 
 
}
<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>

+0

これは機能しました!どうもありがとうございます。申し訳ありませんが、これは初歩的だったと思うので、私はjsを学ぼうとしていますので、たくさんのものが私によってスリップします – anon

+0

@anonあなたはとても歓迎です:)! – HenryDev