Javascriptトランプで一枚ずつカードを並べていきたく、
まず最初に、
ボタンを押すと1から5の数字をランダムに並べていくコードを作ろうと思いました。
しかし、下記のコードだと、ランダムに1枚の数字を出してくれるのですが、並べて書けません。
ul.appendChild(li要素)とすると、どんどん下に数字が並んでいくと思っていたら、最初の一枚の数字が入れ替わるだけになってしまいました。
どのようにしたら
・1
・3
・5
・4
・2
このように数字を並べられるでしょうか?
ご教授ください。
javascript
1<!DOCTYPE html> 2<html> 3 <head> 4 <meta charset="utf-8"> 5 <title>Thimble Sample</title> 6 <link rel="stylesheet" href="style.css"> 7 </head> 8 <body> 9 <button id="btn">ボタン</button> 10 <ul id="output"> 11 </ul> 12 <script> 13 const btn = document.getElementById('btn'); 14 const output = document.getElementById('output'); 15 const li = document.createElement('li') 16 const nums = [1,2,3,4,5] 17 btn.addEventListener('click', () => { 18 const num = nums.splice(Math.floor(Math.random()*nums.length),1)[0]; 19 console.log(nums); 20 console.log(num); 21 li.textContent = num 22 output.appendChild(li); 23 }); 24 </script> 25 </body> 26</html> 27
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/06/10 23:30