HTMLで座席表を作りJavaScriptを使って画面をクリックしたら色と画面の表示が変わる処理をしています。
9席すべてに同様の処理を行いたいのですが、1席しか処理ができません。
調べた結果すべての要素を取得できるquerySelectorAllを使ってfor文で回すというやり方を見つけて実装してみたのですがうまく処理ができない状況です。
どのようにすればすべての座席に処理を実装できるか教えていただきたいです。
HTML
<body> <table> <tr> <td id="btn"><button><p>在席中</p></button><p>A</p></td> <td id="btn"><button><p>在席中</p></button><p>B</p></td> <td id="btn"><button><p>在席中</p></button><p>C</p></td> <td id="btn"><button><p>在席中</p></button><p>D</p></td> <td rowspan = "5" width = 120 id="btn"><button>在席中</button><p>E</p></td> </tr> <tr> <td id="btn"><button><p>在席中</p></button><p>E</p></td> <td id="btn"><button><p>在席中</p></button><p>F</p></td> <td id="btn"><button><p>在席中</p></button><p>G</p></td> <td id="btn"><button><p>在席中</p></button><p>H</p></td> </tr> </table> <script src="./sample.js"> </script> </body>
JavaScript
window.addEventListener('DOMContentLoaded', function(e){ var btn=document.querySelectorAll('#btn'); for(var i = 0; i < btn.length; i++){ btn[i].style.backgroundColor='red'; btn[i].dataset['color']='red'; btn[i].addEventListener('click',function(){ switch(btn[i].dataset['color']){ case 'red': btn.style.backgroundColor='green'; btn.dataset['color']='green'; btn.querySelector('p').textContent='会議中'; break; case 'green': btn.style.backgroundColor='blue'; btn.dataset['color']='blue'; btn.querySelector('p').textContent='在席中'; break; default: btn.style.backgroundColor='red'; btn.dataset['color']='red'; btn.querySelector('p').textContent='外出中'; break; } }); } });
まだ回答がついていません
会員登録して回答してみよう