Показать сообщение отдельно
  #17 (permalink)  
Старый 19.09.2018, 12:55
Профессор
Отправить личное сообщение для Nexus Посмотреть профиль Найти все сообщения от Nexus
 
Регистрация: 04.12.2012
Сообщений: 3,800

giwuf,
<form id="vote" action="#" method="POST">
    <div id="content">
        <div class="pattern">
            <h4 class="question">{% question %}</h4>
            <div class="answers">
                <div class="radio"><label><input type="radio" name="poll[{% id %}]" value="{% answer.value %}">{% answer.title %}</label></div>
            </div>
        </div>
    </div>
    <div><button type="submit" class="btn btn-default">Ответить</button></div>
</form>
<script>
	$.getJSON('/path/to/you-json',function(data){
		data=(typeof data==='string')?JSON.parse(data):data;
		
		const content = document.getElementById('content');
		const patternNode = content.querySelector('.pattern');

		patternNode.classList.remove('pattern');
		const pattern = patternNode.outerHTML;
		patternNode.parentNode.removeChild(patternNode);

		data.forEach(function(question, index) {
			content.insertAdjacentHTML('beforeEnd', pattern.replace(/{%\s?question\s?%}/gim, question.question));
			const questionNode = content.lastChild;
			questionNode.dataset.index = index;
			questionNode.style.display = 'none';
			const answers = questionNode.querySelector('.answers');
			const answer = answers.querySelector('.radio').outerHTML;
			answers.innerHTML = question.answers.map(function(title, value) {
				return answer
					.replace(/{%\s?id\s?%}/gim, question.id)
					.replace(/{%\s?answer.title\s?%}/gim, title)
					.replace(/{%\s?answer.value\s?%}/gim, value);
			}).join("\n");
		});

		let currentQuestionIndex = 0;
		const questions = [].slice.call(content.querySelectorAll('[data-index]'));
		questions[0].style.display = 'block';

		document.querySelector('#vote [type="submit"]').addEventListener('click', function(e) {
			questions[currentQuestionIndex].style.display = 'none';
			if (++currentQuestionIndex >= questions.length)
				return;

			e.preventDefault();
			questions[currentQuestionIndex].style.display = 'block';
		});
	});
</script>

Последний раз редактировалось Nexus, 19.09.2018 в 13:27.
Ответить с цитированием