У меня есть динамическая анкета, в которой респондент должен сортировать некоторые ответы по порядку. Первоначальный подход был примерно таким.
Из моего бэкэнда Django я заполняю страницу всеми вопросами/ответами/типами и т. д., а также вопросами по страницам. Я сократил типы и избавил код от форматирования. Надеюсь, за этим можно следить.
Код: Выделить всё
var to_drag=null
function generateQ(q_id,Section) {
const questionObj = QData.find(q => q.q_id === q_id);
if (questionObj) {
// Example: Create a new div and append the question to it
const div = document.createElement("div");
div.setAttribute("id", `${Section}_${q_id}`);
p.textContent = questionObj.question; // Set the question text
div.appendChild(p);
// Set the alternative answers
if (questionObj.answerType !== 'Sor' && questionObj.choices) {
const choices = questionObj.choices.split(',');
choices.forEach(choice => {
const input = document.createElement("input");
const label = document.createElement("label");
input.setAttribute("type", "checkbox");
label.textContent = choice;
}
if (questionObj.answerType === 'Sor' && questionObj.choices) {
const choices = questionObj.choices.split(',');
//create fields to drop
choices.forEach(choice => {
let drag_id=q_id+'_'+choice
const drag = document.createElement("drag");
drag.textContent = choice;
drag.setAttribute("draggable", "true");
drag.setAttribute("name", drag_id);
div.appendChild(drag)
});
//create tabel to to drop to
const table = document.createElement("table");
let nmbr = choices.length;
for (let i = 0; i < nmbr; i++) {
const row = document.createElement("tr");
const cell = document.createElement("td");
let drag_to_id = q_id+'_'+i
cell.setAttribute("name", drag_to_id);
row.appendChild(cell);
table.appendChild(row);
}
div.appendChild(table);
}
}
window.onload = function() {
if (page_1.length>0) {
page_1.forEach(q_id => {
generateQ(q_id,'p_1')
});
document.getElementById('p_1').style.display = "";
}
.....
};
document.addEventListener("DOMContentLoaded", () => {
to_drag=document.getElementsByTagName('drag')
//then do something for the draggable items.
for (let i = 0; i < to_drag.length; i++) {
//..my code for dragging
}
});
Подробнее здесь: https://stackoverflow.com/questions/798 ... s-using-js
Мобильная версия