我正在尝试在 Spring 中创建一个应用程序,用户在其中设计一个测验。他们通过使用 Thymeleaf 表单提交问题来创建测验。 “Question”是一个具有一些不同属性的类,但为了简单起见,我只关注添加问题本身,即一个名为“questionPrompt”的字符串。提交表单后,每个问题应保存在 QuestionList(Quiz 类中的 ArrayListtype 属性)的下一个可用索引中。
添加到表单中的问题数量由用户决定。因此,我创建了一个 J 查询方法,用户可以在其中生成新问题。单击“克隆并追加”按钮时,将为下一个问题生成一个新文本框,并且标签和 ID 更新为唯一。此方法的工作原理是克隆问题模板并将其附加到空 div。
我面临的问题是我无法成功更新 th:field。更新此字段将允许我将每个问题单独保存在 QuestionList 的下一个可用索引中。相反,在提交表单时,每个单独文本框中的文本将连接起来并保存为同一索引中的单个问题。例如。你喜欢长片吗?,你喜欢恐怖片吗?
我认为我的问题与 J-Query 无法正确使用 Thymeleaf 属性有关,但我不知道如何修复它。任何帮助将不胜感激!
HTML:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Create Quiz</title>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script>
$(document).ready(function () {
var questionCounter = 1;
var originalExpression = "*{quiz.quizQuestion[0].prompt}";
// When the document is ready, execute the following code
$("#cloneButton").click(function () {
// When the button with id "cloneButton" is clicked, execute the following code
var originalDiv = $("#questionContainer");
// .clone() clones the contents of #cloneContainer instead of the container itself.
var clonedDiv = $("#cloneContainer").clone();
var newId = "cloneContainer" + questionCounter;
// var newLabel ="Question: " + questionCounter;
clonedDiv.attr("id", newId);
var newLabel = "Question: " + (questionCounter + 1);
clonedDiv.find("label").text(newLabel);
// clonedDiv.find("input").attr("th:field", "*{quiz.quizQuestion[" + questionCounter + "].prompt}");
var targetElement = clonedDiv.find(":contains('" + originalExpression + "')");
var newExpression = "*{quiz.quizQuestion[" + questionCounter + "].prompt}";
alert(newExpression);
clonedDiv.html(clonedDiv.html().replace(originalExpression, newExpression));
clonedDiv.find("input").val("*{quiz.quizQuestion[" + questionCounter + "].prompt}");
originalDiv.append(clonedDiv);
questionCounter++;
});
});
</script>
</head>
<body>
<form th:action="@{/api/v1/quiz/registerQuiz}" method="post">
<div id="cloneContainer">
<label> Question: 1 </label> <input type="text" th:field="*{quiz.quizQuestion[0].prompt}" />
</div>
<div id="questionContainer"></div>
<div>
<button type="button" id="cloneButton">Clone and Append</button>
</div>
<div>
<input type="submit" value="Submit">
</div>
</form>
</body>
</html>
为每个输入设置适当的名称属性。
clonedDiv.find('input').prop('name', `quiz.quizQuestion[${questionCounter}].prompt`);