Тест на js: чтобы без правильного ответа не было возможно перейти к след. вопросу.
Доброго времени суток! Есть тест, в котором несколько вопросов и в каждом только 1 вариант ответа может быть верным (см. код ниже), после каждого ответа на вопрос выдается правильный вариант ответа.
Подскажите, пожалуйста, как сделать, чтобы не было возможности перейти к следующему вопросу, пока не тыкнешь на правильный ответ в текущем варианте? Ну а если ответил неправильно, то также выдается предупреждение, что ответ неправильный :help: <!DOCTYPE html> <html lang="ru-RU"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Тест на javascript </title> <style> body{ font-family:verdana; color:#444; } #option1,#option2,#option3,#option4{ display:none; margin-bottom: 10px; } .oganesyan{ text-decoration: none; font-size: 20px; margin-right: 20px; color: #fff; background: #3C8FB7; padding: 4px 8px; border: 0; cursor: pointer; } </style> <script type="text/javascript"> //Массив вопросов и ответа var data_array = [ ["Сколько сантиметров в метре?","10","1024","100","1000",3], ["Перевод слова: Hello","Как дела?","Привет","Ты","Дом",2], ["Перевод слова: Dog","Собака","Кошка","Дерево","Сосиска",1], ["Сколько месяцев в году?","10","11","12","13",3], ["Перевод слова: Tree","Три","Собака","Дерево","Дом",3], ["Перевод слова: Wall","Стена","Дом","Башня","Война",1], ]; var plus = 0; var time = 0; var cur_answer = 0; var count_answer = data_array.length; function sec() { time++; document.getElementById('time').innerHTML='Затрачено времени: ' + time + ' сек'; } function check(num){ if(num == 0){ document.getElementById('option1').style.display='block'; document.getElementById('option2').style.display='block'; document.getElementById('option3').style.display='block'; document.getElementById('option4').style.display='block'; document.getElementById('question').style.display='block'; document.getElementById('option1').innerHTML=data_array[cur_answer][1]; document.getElementById('option2').innerHTML=data_array[cur_answer][2]; document.getElementById('option3').innerHTML=data_array[cur_answer][3]; document.getElementById('option4').innerHTML=data_array[cur_answer][4]; document.getElementById('question').innerHTML=data_array[cur_answer][0]; document.getElementById('start').style.display='none'; document.getElementById('end').style.display='inline'; var intervalID = setInterval(sec, 1000); }else{ if( num == data_array[cur_answer][5]){ plus++; document.getElementById('result').innerHTML='Верно!'; }else{ document.getElementById('result').innerHTML="Неверно! Правильный ответ: " + data_array[cur_answer][data_array[cur_answer][5]]; } cur_answer++; if(cur_answer < count_answer){ document.getElementById('option1').innerHTML=data_array[cur_answer][1]; document.getElementById('option2').innerHTML=data_array[cur_answer][2]; document.getElementById('option3').innerHTML=data_array[cur_answer][3]; document.getElementById('option4').innerHTML=data_array[cur_answer][4]; document.getElementById('question').innerHTML=data_array[cur_answer][0]; }else{ document.getElementById('time').id = 'stop'; document.getElementById('option1').style.display='none'; document.getElementById('option2').style.display='none'; document.getElementById('option3').style.display='none'; document.getElementById('option4').style.display='none'; document.getElementById('question').style.display='none'; document.getElementById('end').style.display='inline'; var percent = Math.round(plus/count_answer*100); var res = 'Плохо!'; if(percent>70) res = 'Хорошо!'; if(percent==100) res = 'Отлично!'; document.getElementById('result').innerHTML='Правильных ответов: ' + plus + ' из ' + count_answer + ' (' + percent + '%)<br>' + res; } } } </script> </head> <body> <center> <p style="font-size: 38px;font-weight: bold;padding-top: 2px;" id="time">Затрачено времени: 0 сек</p> <p style="font-size: 38px;font-weight: bold;padding-top: 2px;" id="result"></p> <p style="font-size: 38px;font-weight: bold;padding-top: 2px;" id="question"></p> <button onclick="check(1)" class="oganesyan" id="option1"></button> <button onclick="check(2)" class="oganesyan" id="option2"></button> <button onclick="check(3)" class="oganesyan" id="option3"></button> <button onclick="check(4)" class="oganesyan" id="option4"></button> </center><br> <center> <button id="start" class="oganesyan" onclick="check(0)">Приступить к тесту</button> <script type="text/javascript"> var curent_url = document.URL; document.write("<a id='end' style='display: none;' class='oganesyan' href='" + curent_url + "'>Начать сначала</a>"); </script> </center> </body> </html> |
Цитата:
|
Текст заменю, это не проблема. Суть вопроса немного в другом, заставить человека до победного отвечать, тест будет для малышей, а при неправильном ответе потом допишу подсказки и т.п.
Вот вариант, где только после правильного ответа выдается подтверждение, а если неправильный - то просьба ответить еще раз: <!DOCTYPE html> <html lang="ru-RU"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Тест на javascript </title> <style> body{ font-family:verdana; color:#444; } #option1,#option2,#option3,#option4{ display:none; margin-bottom: 10px; } .oganesyan{ text-decoration: none; font-size: 20px; margin-right: 20px; color: #fff; background: #3C8FB7; padding: 4px 8px; border: 0; cursor: pointer; } </style> <script type="text/javascript"> //Массив вопросов и ответа var data_array = [ ["Сколько сантиметров в метре?","10","1024","100","1000",3], ["Перевод слова: Hello","Как дела?","Привет","Ты","Дом",2], ["Перевод слова: Dog","Собака","Кошка","Дерево","Сосиска",1], ["Сколько месяцев в году?","10","11","12","13",3], ["Перевод слова: Tree","Три","Собака","Дерево","Дом",3], ["Перевод слова: Wall","Стена","Дом","Башня","Война",1], ]; var plus = 0; var time = 0; var cur_answer = 0; var count_answer = data_array.length; function sec() { time++; document.getElementById('time').innerHTML='Затрачено времени: ' + time + ' сек'; } function check(num){ if(num == 0){ document.getElementById('option1').style.display='block'; document.getElementById('option2').style.display='block'; document.getElementById('option3').style.display='block'; document.getElementById('option4').style.display='block'; document.getElementById('question').style.display='block'; document.getElementById('option1').innerHTML=data_array[cur_answer][1]; document.getElementById('option2').innerHTML=data_array[cur_answer][2]; document.getElementById('option3').innerHTML=data_array[cur_answer][3]; document.getElementById('option4').innerHTML=data_array[cur_answer][4]; document.getElementById('question').innerHTML=data_array[cur_answer][0]; document.getElementById('start').style.display='none'; document.getElementById('end').style.display='inline'; var intervalID = setInterval(sec, 1000); }else{ if( num == data_array[cur_answer][5]){ plus++; document.getElementById('result').innerHTML='Верно!'; }else{ document.getElementById('result').innerHTML="Неверно! Попробуй еще раз :) "; } cur_answer++; if(cur_answer < count_answer){ document.getElementById('option1').innerHTML=data_array[cur_answer][1]; document.getElementById('option2').innerHTML=data_array[cur_answer][2]; document.getElementById('option3').innerHTML=data_array[cur_answer][3]; document.getElementById('option4').innerHTML=data_array[cur_answer][4]; document.getElementById('question').innerHTML=data_array[cur_answer][0]; }else{ document.getElementById('time').id = 'stop'; document.getElementById('option1').style.display='none'; document.getElementById('option2').style.display='none'; document.getElementById('option3').style.display='none'; document.getElementById('option4').style.display='none'; document.getElementById('question').style.display='none'; document.getElementById('end').style.display='inline'; var percent = Math.round(plus/count_answer*100); var res = 'Плохо!'; if(percent>70) res = 'Хорошо!'; if(percent==100) res = 'Отлично!'; document.getElementById('result').innerHTML='Правильных ответов: ' + plus + ' из ' + count_answer + ' (' + percent + '%)<br>' + res; } } } </script> </head> <body> <center> <p style="font-size: 38px;font-weight: bold;padding-top: 2px;" id="time">Затрачено времени: 0 сек</p> <p style="font-size: 38px;font-weight: bold;padding-top: 2px;" id="result"></p> <p style="font-size: 38px;font-weight: bold;padding-top: 2px;" id="question"></p> <button onclick="check(1)" class="oganesyan" id="option1"></button> <button onclick="check(2)" class="oganesyan" id="option2"></button> <button onclick="check(3)" class="oganesyan" id="option3"></button> <button onclick="check(4)" class="oganesyan" id="option4"></button> </center><br> <center> <button id="start" class="oganesyan" onclick="check(0)">Приступить к тесту</button> <script type="text/javascript"> var curent_url = document.URL; document.write("<a id='end' style='display: none;' class='oganesyan' href='" + curent_url + "'>Начать сначала</a>"); </script> </center> </body> </html> |
Globus,
строка 77 добавить return} |
Всё гениальное - просто! Спасибо)
|
Ещё один момент - всё отлично, только при правильном ответе сразу же под надписью 'Верно!' пишется следующий вопрос и это немного смущает. Можно как-то приостанавливать тест, например, выдается надпись 'Верно!' и внизу кнопка "Перейти к следующему вопросу"?
Подскажите, пожалуйста, если не сложно, как это можно решить? По аналогии поставил return ещё и в начале 75 строки, тогда выдается надпись о верном ответе, но к следующему вопросу не знаю, как перейти.. ... if( num == data_array[cur_answer][5]){ plus++; document.getElementById('result').innerHTML='Верно!'; return }else{ document.getElementById('result').innerHTML="Неверно! Попробуй еще раз :) "; return } ... |
вопросник кнопка next
Globus,
<!DOCTYPE html> <html> <head> <title>Untitled</title> <meta charset="utf-8"> <style type="text/css"> .slider { text-align: center; } .slider ul { list-style: none; margin: 20px auto; padding: 0; } .slider ul li { font-size: 20px; margin: 20px auto; color: #fff; background-color: #3c8fb7; border: 0; cursor: pointer; width: 100px; } .slider ul li:first-child { width: 90%; display: block; background-color: transparent; color: #000; font-size: 38px; font-weight: bold; padding-top: 2px; cursor: default; } .slider.ok ~ .btn{ display: block; } .btn { margin: 20px auto; width: 100px; display: none; } .ok li.yes { background-color: #f00; } </style> <script> window.addEventListener("DOMContentLoaded", function() { function createHTML(data) { var k = data.pop(); return data.reduce(function(html, text, i) { var li = i == k ? "<li class='yes'>" : "<li>"; return html + li + text; }, "<ul>"); } var arr = [ ["Сколько сантиметров в метре?","10","1024","100","1000",3], ["Перевод слова: Hello","Как дела?","Привет","Ты","Дом",2], ["Перевод слова: Dog","Собака","Кошка","Дерево","Сосиска",1], ["Сколько месяцев в году?","10","11","12","13",3], ["Перевод слова: Tree","Три","Собака","Дерево","Дом",3], ["Перевод слова: Wall","Стена","Дом","Башня","Война",1], ]; var node = document.querySelector(".slider"), btn = document.querySelector(".btn"); btn.addEventListener("click", function() { var html = arr.length ? createHTML(arr.shift()) : "ваш результат"; node.innerHTML = html; node.classList.remove("ok"); }); node.addEventListener("click", function(event) { if(node.classList.contains("ok")) return; var target = event.target; if (target.tagName == "LI") { var index = [].indexOf.call(node.querySelectorAll("li"), target); if (index && target.classList.contains("yes")) { node.classList.add("ok"); } else { if (index) { alert("Неверно! Попробуй еще раз :)"); } } } }); }); </script> </head> <body> <div class="slider ok">что пройти тест нажмите кнопку ниже</div> <button class="btn" type="button" >next</button> </body> </html> |
Спасибо! А я сделал next, повесив на эту кнопку кусок кода, который после cur_answer++; идёт)
Но ваше решение элегантнее) |
Цитата:
|
Часовой пояс GMT +3, время: 19:50. |