【发布时间】:2017-11-13 04:56:33
【问题描述】:
我正在尝试输入一个问题并将该问题显示为表单中的一个元素,"survey-form"。但是,当我使用 JavaScript 将子节点附加到 "survey-form" 时,文本会出现半秒钟然后消失。似乎标签元素已附加但随后被删除。关于如何解决这个问题的任何想法?
window.onload = init;
function init() {
document.getElementById("question-form").addEventListener("submit",
validateQuestion);
}
function validateQuestion() {
let questionValue = document.getElementById("question-box").value;
if (questionValue == "" || questionValue == undefined) {
alert("Fill the box with information so it can be added to the survey!");
return;
} else {
addQuestion(questionValue);
}
}
function addQuestion(question) {
let label = document.createElement("label");
label.innerHTML = question;
document.getElementById("survey-form").appendChild(label);
}
<!DOCTYPE html>
<html>
<head>
<title>Create Your Own Survey</title>
<link rel="stylesheet" type="text/css" href="index.css">
<script type="text/javascript" src="index.js"></script>
</head>
<body>
<div id="model-side">
<form id="question-form" method="" action="">
<label>Create a question for the survey:</label>
<input id="question-box" type="text" size="35" /><br/>
<input type="submit" value="Submit Question" />
</form>
</div>
<div id="view-side">
<form id="survey-form" method="" action="">
<label>Current View</label>
</form>
</div>
</body>
</html>
【问题讨论】:
-
使用 event.preventDefault();在 validateQuestion 函数中。
标签: javascript forms dom appendchild