ボタンを押すと13~18のランダムな数字を出力したい場合、どのようにやればいいのかを考えております。
自分なりに考えてはみましたが、どのやり方が自然、不自然、ありえないのか?
皆様のご意見をいただけたら幸いです。
ボタン2やボタン3は、13~18という範囲が今後変更になる際にやりやすい方法として考えてみました。特にボタン3は編集はしやすいのですが、どうにも無駄な動きが多い気がしまして、これらコードを見て、納得なのか、ありえないな!変!と思うのか、他にどんなやり方があるのか?ご意見をいただけたら幸いです。
html
1<!DOCTYPE> 2<html lang="ja"> 3 <head> 4 <meta charset="utf-8"> 5 <link rel="stylesheet" href="styles.css"> 6 </head> 7 <body> 8 <div id="target">?</div> 9 <button id="btn1">ボタン1</button> 10 <button id="btn2">ボタン2</button> 11 <button id="btn3">ボタン3</button> 12 <script> 13 { 14 'use strict' 15 const target = document.getElementById("target"); 16 const btn1 = document.getElementById("btn1"); 17 const btn2 = document.getElementById("btn2"); 18 const btn3 = document.getElementById("btn3"); 19 20 btn1.addEventListener('click', ()=>{ 21 const result = [13,14,15,16,17,18]; 22 const num = Math.floor(Math.random() * result.length); 23 target.textContent = result[num]; 24 }); 25 26 btn2.addEventListener('click', ()=>{ 27 const num_length = Math.floor(Math.random() * 6);//0-5 28 const answer2 = num_length + 13//13-18 29 target.textContent = answer2; 30 }); 31 32 btn3.addEventListener('click', ()=>{ 33 let answer3; 34 do { 35 answer3 = Math.floor(Math.random() * 18 + 1 );//1-18 36 }while(answer3 < 13) 37 target.textContent = answer3; 38 }); 39 40 41 } 42 </script> 43 </body> 44</html>
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/04/23 05:54
2019/04/23 06:12