前提・実現したいこと
Javascriptを使って性格診断テストを作りたい。
まだ完成ではなく
『複数クリックしても最後のものだけ色を付けるようにする。』
『入力したものをデータベースに取り込む』
という所のイメージがついていません。
特にさわったばかりで、JavaScriptで選択したデータはデータベースにそもそも取り込めるのかもわかりません。どういった関数でプログラムを作っていけるんでしょうか?
また、最後のものだけに色を付けるやり方も今のクラスを付与する形のものをいじくったらできますでしょうか?
そもそも診断テストならもっと簡単な形がいいんでしょうか(^-^;
該当のソースコード
JavaScript
1'use strict'; 2 3{ 4 const question = document.getElementById('question'); //constで値を変えないものとして代入 5 const btn = document.getElementById('btn'); //getElementById指定したIDに会ったドキュメントを取得 6 const choices = document.getElementById('choices'); // 7 8 const quizSet = [ 9 {q: 'What is A?', c: ['A0', 'A1', 'A2']}, 10 {q: 'What is B?', c: ['B0', 'B1', 'B2']}, 11 {q: 'What is D?', c: ['C0', 'C1', 'C2']}, 12 {q: 'What is E?', c: ['C0', 'C1', 'C2']}, 13 {q: 'What is F?', c: ['C0', 'C1', 'C2']}, 14 {q: 'What is G?', c: ['C0', 'C1', 'C2']}, 15 {q: 'What is H?', c: ['C0', 'C1', 'C2']}, 16 {q: 'What is I?', c: ['C0', 'C1', 'C2']}, 17 {q: 'What is J?', c: ['C0', 'C1', 'C2']}, 18 ]; 19 let currentNum = 0; 20 let isAnswered; 21 22 function shuffle(arr) { 23 return arr; 24 } 25 26 function checkAnswer(li) { 27 if(isAnswered){ 28 return; 29 } 30 li.classList.add('correct'); 31 btn.classList.remove('disabled'); 32 } 33 function setQuiz() { 34 isAnswered = false; 35 36 question.textContent = quizSet[currentNum].q; 37 38 while (choices.firstChild) { 39 choices.removeChild(choices.firstChild); 40 } 41 42 const shuffledChoices = shuffle([...quizSet[currentNum].c]); 43 shuffledChoices.forEach(choice => { //アロー関数? 44 const li = document.createElement('li'); 45 li.textContent = choice; 46 li.addEventListener('click', () => { 47 checkAnswer(li); 48 }); 49 choices.appendChild(li); 50 }); 51 } 52 53 setQuiz(); 54 btn.addEventListener('click', () => { 55 currentNum++; 56 setQuiz(); 57 }); 58}
HTML
1 <div class ="container2"> 2 <p id="question"></p> 3 <ul id="choices"></ul> 4 <div id="btn" class="disabled">Next</div> 5 </div>
CSS
1/* 診断テスト*/ 2.container2 { 3 width: 400px; 4 margin: 8px auto; 5 background: #fff; 6 border-radius: 4px; 7 padding: 16px; 8 position: relative; 9} 10 11#question{ 12 margin-bottom: 16px; 13 font-weight: bold; 14} 15 16#choices { 17 list-style: none; 18 padding: 0; 19 margin-bottom: 16px; 20} 21 22#choices li{ 23 border: 1px solid #ccc; 24 border-radius: 4px; 25 padding: 10px; 26 margin-bottom: 10px; 27 cursor: pointer; 28} 29 #choices li:hover { 30 background: #f8f8f8; 31} 32 33 #choices li.correct{ 34 background: #d4edda; 35 border-color: #c3e6cd; 36 color: #155724; 37 font-weight: bold; 38 } 39 40#btn{ 41 background: #3498db; 42 padding: 8px; 43 border-radius: 4px; 44 cursor: pointer; 45 text-align: center; 46 color: #fff; 47 box-shadow: 0 4px 0 #2880b9; 48} 49#btn.disabled{ 50 background: #ccc; 51 box-shadow: 0 4px 0 #bbb; 52 opacity: 0.7; 53}
試したこと
サンプルやテキストを参考に少しいじくって形は完成ではないですが、一応作れました。
回答2件
あなたの回答
tips
プレビュー